導入相關模塊
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
基本圖表
散點圖:scatter
N = 1000
x = np.random.randn(N)
y = np.random.randn(N)
plt.scatter(x,y)
plt.show()
scatter的函數簽名如下
scatter(x,y,s=None,c=None,marker=None,cmap=None,norm=None,vmin=None,vmax=None,alpha=None,linewidths=None,verts=None,edgecolors=None,hold=None,data=None,**kwargs)
- x,y:形如shape(n,)的數組
- s:點的大小,默認20
- c:點的取色序列,默認藍色
- marker:點的形狀,默認是圓(具體的點的形狀可以在matplotlib的官網中搜索markers查看。)
- alpha:點的透明度
- edgecolors:邊緣顏色
plt.scatter(x,y,c='rykgm',s=100,marker='>')
plt.show()
plt.scatter(x,y,alpha=0.5)
plt.show()
plt.scatter(x,y,edgecolors='r')
plt.show()
柱狀圖:bar
data = [5, 20, 15, 25, 10]
plt.bar(range(len(data)), data)
plt.show()
bar的函數簽名如下:
bar(left, height, width=0.8, bottom=None, **kwargs)
事實上,left,height,width,bottom這四個參數確定了柱體的位置和大小,具體定位如下:
- (left - width / 2, bottom)為左下角位置
- (left + width / 2, bottom + height)為右上角位置
plt.bar([0.3,1.7,4,6,7], data, width=0.6,bottom=[10,0,5,0,5])
plt.show()
對於柱狀圖,還可以設置以下參數:
- 顏色:color
- 描邊:edgecolor(ec):邊緣顏色;linestyle(ls):邊緣樣式;linewidth(lw):邊緣粗細
- 填充:hatch:可取值為: / , \ , | , - , + , x , o , O , . , *
- 位置標志:tick_label
labels = ['Tom', 'Dick', 'Harry', 'Slim', 'Jim']
plt.bar(range(len(data)),data, color='rgb',ec='r',ls='--',lw=2,hatch='o',tick_label=labels)
plt.show()
堆疊柱狀圖
通過bottom參數,可以輕松實現堆疊柱狀圖
size = 5
x = np.arange(size)
a = np.random.random(size)
b = np.random.random(size)
plt.bar(x, a, label='a')
plt.bar(x, b, bottom=a, label='b')
plt.legend()
plt.show()
並列柱狀圖
並列柱狀圖則需要通過left屬性添加偏移量來實現
total_width, n = 0.8, 2
width = total_width / n
x = x - (total_width - width) / 2
plt.bar(x, a, width=width, label='a')
plt.bar(x + width, b, width=width, label='b')
plt.legend()
plt.show()
條形圖
類似bar方法,僅換了方法名稱:barh(bar-horizontal)
plt.barh(range(len(data)), data)
plt.show()
barh的簽名為
barh(bottom, width, height=0.8, left=None, **kwargs)
因此,使用時可以看成是bar的旋轉,其方法完全一樣
正負條形圖
可以通過barh方法輕松獲得
a = np.array([5, 20, 15, 25, 10])
b = np.array([10, 15, 20, 15, 5])
plt.barh(range(len(a)), a)
plt.barh(range(len(b)), -b)
plt.show()
折線圖:plot
a = np.array([5, 20, 15, 25, 10])
plt.plot(a)
plt.show()
和柱狀圖類似,plot也提供了一些常用的參數,折線圖含有兩種對象:點和線,因此,可以分別對點和線進行設置,對線的設置與柱狀圖類似,參數有ls、lw;對點的設置可以參照scatter中的參數,為了區分點和線,規定在點參數前添加一個字母m(marker)來表示,至於線的顏色,可以通過color(c)參數來設置。因此,一個簡單的參數設置可以如下表示:
plt.plot(a, color='r',ls='--',lw=2,marker='o',mec='b',ms=10, mfc='w')
plt.show()
plot還提供了一個更簡潔的方法:合並color、marker、linestyle三個參數為一個字符串,方便設置。
plt.plot(a,'ro--')
plt.show()
在做數據可視化的時候,常用的基本圖表有折線圖、散點圖和柱狀圖三種,其它諸如餅圖、箱形圖等出現較少,第一部分暫不處理。有了這些圖標已經可以做一些基本的分析了,下一節中,將介紹一些常用的設置,諸如坐標軸、標簽等。