【數(shù)據(jù)可視化】Matplotlib用法(附實(shí)例)

?? 一、Matplotlib庫(kù)相關(guān)介紹

【介紹】:Matplotlib 是建立在Numpy數(shù)組基礎(chǔ)上的多平臺(tái)數(shù)據(jù)可視化程序庫(kù)。

?? 二、設(shè)置圖形標(biāo)簽

【第一種】:MATLIB 風(fēng)格
plt.plot(x,np.sin(x))
plt.title("A Sine Curve")
plt.xlabel("x")
plt.ylabel("sin(x)")
MATLIB 風(fēng)格
【第二種】:面向?qū)ο箫L(fēng)格
# 設(shè)置時(shí),要做如下形式的變換
#plt.xlabel => ax.set_xlabel
ax = plt.axes()
ax.plot(x,np.sin(x))
ax.set_xlabel("x")
ax.set_ylabel("sin(x)")
ax.set_title('A Sine Curve')
面向?qū)ο箫L(fēng)格

?? 三、設(shè)置圖例

【第一步】:繪制圖例(參數(shù)為:label)
plt.plot(x,np.sin(x),'-g',label="sin(x)")
plt.plot(x,np.cos(x),':b',label="cos(x)")

#顯示圖例
plt.legend()
顯示圖例
【第二步】:配置圖例
x = np.linspace(0,10,1000)
fig,ax = plt.subplots()
ax.plot(x,np.sin(x), '-b', label="Sine")
ax.plot(x,np.cos(x),'--r', label="Cosine")
ax.axis('equal')

leg = ax.legend(loc='upper left',frameon=False, ncol=2)

【注釋】:Matplotlib中顯示圖形時(shí)調(diào)用legend()函數(shù),其中有以下幾個(gè)較為常用的參數(shù)

  • loc: 位置參數(shù);
  • frameon: 去掉邊框;
  • ncol: 圖例的列數(shù);
配置圖例
【第三步】:其他配置
x = np.linspace(0,10,1000)
fig,ax = plt.subplots()
ax.plot(x,np.sin(x), '-b', label="Sine")
ax.plot(x,np.cos(x),'--r', label="Cosine")
ax.axis('equal')
- fancybox:圓角邊框
- framealpha: 邊框的透明度
- shadow:陰影
- borderpad:邊距
leg = ax.legend(fancybox=True, framealpha=0.5, shadow=True,borderpad=1)

【注釋】:Matplotlib中顯示圖形時(shí)調(diào)用legend()函數(shù),其中有以下幾個(gè)較為常用的參數(shù):

  • fancybox:圓角邊框;
  • framealpha: 邊框的透明度;
  • shadow:陰影;
  • borderpad:邊距;
output_相關(guān)配置
【第四步】:設(shè)置多個(gè)圖例
fig,aix = plt.subplots()
styles = ['-','--','-.',':']
lines = []

x = np.linspace(0,10,1000)
for i in range(4):
    lines += aix.plot(x,np.sin(x - i * np.pi / 2),styles[i],color='black')

# 設(shè)置第一個(gè)圖的圖例
aix.legend(lines[:2],['Line A','Line B'], loc='upper right', frameon=False)

# 設(shè)置第二個(gè)圖例
from matplotlib.legend import Legend
leg = Legend(aix,lines[2:],['LineC','LineD'],loc='lower right',frameon=False)
aix.add_artist(leg)

aix.axis('equal')
plt.show()
output_多個(gè)圖例

?? 四、繪制簡(jiǎn)易散點(diǎn)圖

【第一步】:基本繪制
x = np.linspace(0,10,30)
y = np.sin(x)
# 參數(shù)o用來表示圖形符號(hào)
plt.plot(x,y,'o',color='black')

【解釋】:這里使用參數(shù)o用來表示圖形符號(hào)。

output_基本繪制
【第二步】:設(shè)置樣式

樣式種類有許多,在繪圖過程中,可以更具自己的偏好選擇樣式,主要樣式如下:

rng = np.random.RandomState(0)
for marker in ['o','.',',','x','+','v','^','<','>','s','d']:
    plt.plot(rng.rand(5),rng.rand(5),marker, label="marker='{0}'".format(marker))
    plt.legend(numpoints=1)
    plt.xlim(0,1.8)
output_設(shè)置樣式
【第三步】:同時(shí)畫出點(diǎn)線和折線
plt.plot(x,y,'-ok')
output_點(diǎn)線和折線
【第四步】:散點(diǎn)圖的其他屬性
plt.plot(x,y,'-p',color='gray',markersize=15,linewidth=4,markerfacecolor='white',markeredgecolor='gray',markeredgewidth=2)
  • markersize:對(duì)應(yīng)坐標(biāo)圖形尺寸,這里設(shè)置為15px;
  • linewidth:線條尺寸(粗細(xì)):這里設(shè)置為4px;
  • markerfacecolor:圖形顏色;
  • markeredgecolor:圖形邊框以及線條顏色;
  • markeredgewidth:邊框線尺寸(粗細(xì)),這里設(shè)置為2px;
output_其他屬性
【第五步】:使用 plt.scatter 繪制散點(diǎn)圖

(特點(diǎn)): scatter 與 plot 相比,擁有更高的靈活性,可以控制每個(gè)散點(diǎn)。

# scatter 與 plot 相比,擁有更高的靈活性,可以控制每個(gè)散點(diǎn)。
plt.scatter(x,y,marker='o')
output_scatter繪圖
【第六步】:通過 scater 控制每個(gè)點(diǎn)
rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)
plt.scatter(x,y,c=colors,alpha=0.3,s=sizes,cmap='viridis')

# 顯示顏色條
plt.colorbar()
output_26_1.png

?? 五、基本誤差線圖

x = np.linspace(0,10,50)
dy = 0.8
y = np.sin(x) + dy * np.random.randn(50)
plt.errorbar(x,y,yerr=dy,fmt='.k')
output_誤差線圖

?? 六、等高線圖

【第一步】:繪制基本等高線圖
# 生成坐標(biāo)
def f(x,y):
    return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
x = np.linspace(0,5,50)
y = np.linspace(0,5,40)

# 生成x,y組成坐標(biāo)的集合
X,Y = np.meshgrid(x,y)
z = f(X,Y)
# 繪制圖形
# 當(dāng)只有一種顏色時(shí),實(shí)線表示正數(shù),虛線表示負(fù)數(shù)
plt.contour(X,Y,z,colors='black')
output_基本等高線圖
【第二步】:使用預(yù)定義的配色方案

plt.cm.<Tab>:可以查看有一共有多少種預(yù)定義的配色方案。

# 使用預(yù)定義的配色方案:RdGy紅灰方案
#可以通過plt.cm.<Tab>,來查看一共有哪些方案
plt.contour(X,Y,z,cmap='RdGy')
output_配色
【第三步】:生成帶填充色的等高線圖
# plt.contourf(X,Y,z,cmap='RdGy')
# (參數(shù))10 : 表示等高線的密集程度
plt.contourf(X,Y,z,10,cmap='RdGy')
plt.colorbar()
output_填充色
【第四步】:將等高線渲染成漸變圖

感覺是通過打馬賽克的方式,來實(shí)現(xiàn)模糊化渲染。

# 將數(shù)組z對(duì)應(yīng)的點(diǎn)渲染為圖象
plt.imshow(z,extent=[0,5,0,5],origin='lower',cmap="RdGy")
plt.colorbar()
plt.axis(aspect='image')
output_漸變圖
【第五步】:將等高線圖和漸變圖疊加一起

我們看見的等高線圖當(dāng)然不象這么簡(jiǎn)陋,但是通過Matplotlib可以實(shí)現(xiàn)類似的功能。

contours = plt.contour(X,Y,z,3,colors='black')
plt.clabel(contours,inline=True, fontsize=8)

plt.imshow(z,extent=[0,5,0,5],origin='lower',cmap='RdGy',alpha=0.3)
plt.colorbar()
output_33_1.png

?? 七、頻次直方圖

data = np.random.randn(1000)
plt.hist(data)
plt.show()
output_基本直方圖
【第一步】:設(shè)置直方圖的樣式
plt.hist(data,bins=30,alpha=0.5,histtype='stepfilled',color='steelblue',edgecolor='black')
plt.show()
output_直方圖樣式

案例:

x1 = np.random.normal(0,0.8,1000)
x2 = np.random.normal(-2,1,1000)
x3 = np.random.normal(3,2,1000)

kwargs = dict(histtype="stepfilled",alpha=0.3,bins=40)
plt.hist(x1,**kwargs)
plt.hist(x2, **kwargs)
plt.hist(x3, **kwargs)
plt.show()
output_案例
【第二步】:使用 plt.hist2d()生成二維頻次直方圖

生成兩組符合正太分布、協(xié)方差矩陣為cov的數(shù)據(jù)

# 生成兩組符合正太分布、協(xié)方差矩陣為cov的數(shù)據(jù)
mean = [0,0]
cov = [[1,1],[1,2]]
x, y = np.random.multivariate_normal(mean,cov,10000).T
# 使用hist2d繪制二維頻次直方圖
plt.hist2d(x,y,bins=30,cmap='Blues')
cb = plt.colorbar()
cb.set_label("counts in bins")
output_二維頻次直方圖
【第三步】: 生成六邊形區(qū)間劃分的二維頻次直方圖

默認(rèn)情況下,二維頻次直方圖是由正方形組成的,可以使用plt.hexbin() 方法繪制六邊形組成的二位頻次直方圖。

# 六邊形區(qū)間劃分
plt.hexbin(x,y,gridsize=30,cmap='Blues')
cb = plt.colorbar(label = 'Counts in bins')
output_六邊形區(qū)間劃分

?? 八、多子圖

# 新建一個(gè)子圖
ax1 = plt.axes()
ax2 = plt.axes([0.65,0.65,0.2,0.2])
output_新建一個(gè)子圖
【第一步】:通過 fig.add_axes([xpos,ypos,width,height])創(chuàng)建子圖
fig = plt.figure()
ax1 = fig.add_axes([0.1,0.5,0.8,0.4])
ax2 = fig.add_axes([0.1,0.1,0.8,0.4])
x = np.linspace(0,10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x))
output_多子圖
【第二步】:通過 plt.subplot() 方法創(chuàng)建子圖
# 創(chuàng)建網(wǎng)格子圖
for i in range(1,7):
    plt.subplot(2,3,i)
    plt.text(0.5,0.5,str((2,3,i)),fontsize=18, ha='center')
output_45_0.png
【第二步】:使用 fig.subplots_adjust() 調(diào)整子圖之間的間隔
fig = plt.figure()
fig.subplots_adjust(hspace=0.4,wspace=0.4)
for i in range(1,7):
    plt.subplot(2,3,i)
    plt.text(0.5,0.5,str((2,3,i)),fontsize=18, ha='center')
output_46_0.png
【第二步】:使用 plt.subplots()創(chuàng)建子圖
# plt.subplots()  一行代碼,創(chuàng)建網(wǎng)格
fig,ax = plt.subplots(2,3,sharex='col',sharey='row')
output_47_0.png
# 繪制子圖內(nèi)容
for i in range(2):
    for j in range(3):
        ax[i,j].text(0.5, 0.5, str((i,j)),fontsize=18,ha='center')
fig
output_子圖內(nèi)容
【第二步】:使用 plt.GridSpec() 創(chuàng)建不規(guī)則網(wǎng)格布局

grid = plt.GridSpec(2,3,wspace=0.4, hspace=0.3)
plt.subplot(grid[0,0])
plt.subplot(grid[0,1:])
plt.subplot(grid[1,:2])
plt.subplot(grid[1,2])
output_規(guī)則網(wǎng)格布局

實(shí)例:繪制多軸頻次直方圖

# 創(chuàng)建正太分布的數(shù)據(jù)
mean = [0,0]
cov = [[1,1],[1,2]]
x, y = np.random.multivariate_normal(mean, cov,200).T

# 設(shè)置坐標(biāo)軸和網(wǎng)格的配置方式
fig = plt.figure(figsize=(6,6))
grid = plt.GridSpec(4,4,hspace=0.2, wspace=0.2)
main_ax = fig.add_subplot(grid[:-1,1:])
y_hist = fig.add_subplot(grid[:-1,0],xticklabels=[],sharey=main_ax)
x_hist = fig.add_subplot(grid[-1,1:],xticklabels=[],sharex=main_ax)

# 主坐標(biāo)軸畫散點(diǎn)圖
main_ax.plot(x,y,'ok',markersize=3,alpha=0.2)

# 次坐標(biāo)的頻次直方圖
x_hist.hist(x,40,histtype='stepfilled',orientation='vertical', color='gray')
# 反轉(zhuǎn)y軸
x_hist.invert_yaxis()

y_hist.hist(y,40,histtype='stepfilled',orientation='horizontal', color='gray')
# 反轉(zhuǎn)x軸
y_hist.invert_xaxis()
output_多軸頻次直方圖

?? 九、給圖形添加箭頭和文本

fig,ax = plt.subplots()
x = np.linspace(0,20,1000)
ax.plot(x,np.cos(x))
ax.axis('equal')


ax.annotate('local maximum',xy=(6.28,1),xytext=(10,4),arrowprops=dict(facecolor='black',shrink=0.05))
ax.annotate('local minimum',xy=(5*np.pi,-1),xytext=(2,-6),arrowprops=dict(arrowstyle="->",connectionstyle="angle3,angleA=0,angleB=-90"))
output_箭頭和文本
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容