引入需要的庫:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from numpy.random import randn
code1:
fig=plt.figure(2)
ax1=fig.add_subplot(2,2,1) #為2*2的圖像 ax1為第1個圖像
ax2=fig.add_subplot(2,2,2) #為2*2的圖像 ax1為第2個圖像
ax3=fig.add_subplot(2,2,3) #為2*2的圖像 ax1為第3個圖像
plt.plot(randn(50).cumsum(),'k--') #隨機(jī)生成50個數(shù)赛惩;‘k--’表示線性選項,用于告訴matplotlib繪制黑色虛線圖,并繪繪制在最后一個格子里
ax1.hist(randn(100),bins=20,color='k',alpha=0.4) #bins 表示分為20個箱子, color為設(shè)置fill的顏色 k為黑色,b為藍(lán)色岖常,r為紅色,alpha=0.3設(shè)置透明度
ax2.scatter(np.arange(30),np.arange(30)+3*randn(30),color='r') #散點圖,默認(rèn)顏色為深藍(lán) ,(其他顏色: k為黑色纵散,b為藍(lán)色,r為紅色 )
plt.show()
圖形顯示1:
Figure_2.png
code2:
fig,axes=plt.subplots(2,2,sharex=False,sharey=False)
#sharex=False,sharey=False每個子圖都會有x,y刻度 若True則會盡量共用刻度
for i in range(2):
for j in range(2):
axes[i,j].hist(randn(500),bins=50,color='k',alpha=0.5)
plt.subplots_adjust(wspace=0.2,hspace=0.2) #控制子圖之間的間距的 wspace左右 hspace為上下
plt.savefig("case2.png", dpi=100) #保存子圖隐圾,dpi為設(shè)置圖片的像素
plt.show()
圖形顯示2:
Figure_1.png
code3:
x=np.arange(10)
y=randn(10)*10
print(x)
print(y)
fig=plt.figure()
ax=fig.add_subplot(1,1,1) #為2*2的圖像 ax1為第一個圖像
ax.plot(x,y,'go--',label='Default') #設(shè)置線型虛線,0為折線上加散點 顏色為綠色 green 或者ax.plot(x,y,linestyle='--',color='g'伍掀,marker='o')效果一樣marker為加點;k為黑色 g為綠色
ax.plot(x,y,'k-',drawstyle='steps-post',label='steps-post')
#drawstyle為設(shè)置連接散點的插值方式
plt.xlim([-1,11]) #設(shè)置x的范圍
plt.legend(loc=2) #設(shè)置圖例的位置
plt.savefig("case3.png", dpi=100)
plt.show()
圖形顯示3:
Figure_1.png
code4:
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.plot(np.arange(1000),randn(1000).cumsum(),'b',label='one')
#x為np.arange(1000),y為randn(1000).cumsum()
ax.plot(np.arange(1000),randn(1000).cumsum(),'r-',label='two')
ax.plot(randn(1000).cumsum(),'k',label='three')
ticks=ax.set_xticks([0,250,500,750,1000]) #設(shè)置刻度
labels=ax.set_xticklabels(['one','two','three','four','five'],rotation=30,fontsize='small')
#設(shè)置刻度標(biāo)簽
ax.legend(loc='best')
ax.set_title('My first matplotlib plot')
ax.set_xlabel('stages')
ax.text(416,22,'this is my freestyle',family='monospace',fontsize=20)
#在圖像上添加注釋
plt.savefig("case4.png", dpi=100)
plt.show()
圖形顯示4:
Figure_1.png
參考資料:
matplotlib官網(wǎng):(http://matplotlib.org/gallery.html)