Python--Matplotlib——學習

原文鏈接

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(431)
ax2 = fig.add_subplot(432)
ax3 = fig.add_subplot(433)
ax4 = fig.add_subplot(434)
ax5 = fig.add_subplot(435)
ax6 = fig.add_subplot(436)
ax7 = fig.add_subplot(437)
ax8 = fig.add_subplot(438)
ax9 = fig.add_subplot(439)


"""1、線"""
x = np.linspace(0,np.pi)
y_sin = np.sin(x)
y_cos = np.cos(x)

ax1.plot(x,y_cos,color='red',linewidth=2,markersize=12,marker='+',linestyle='dashed')
ax1.set(title='line')

"""2、點"""
x2=np.arange(10)
x2=np.random.randn(10)
ax2.scatter(x2,x2,color='red',edgecolor='yellow',marker='*')
ax2.set(title='points')


"""3、條狀圖"""
np.random.seed(1) #每次運行代碼時設置相同的seed,則每次生成的隨機數也相同,如果不設置seed,則每次生成的隨機數都會不一樣。
x3=np.arange(5)
y3=np.random.randn(5)  #隨機數、正態分佈
vert_bars=ax3.bar(x3,y3,color='lightblue',align='center')
horiz_bars=ax4.barh(x3,y3,color='lightblue',align='center')

for bar, height in zip(vert_bars, y3):
    if height < 0:
        bar.set(edgecolor='darkred', color='red', linewidth=3)
for bar, height in zip(horiz_bars, y3):
    if height < 0:
        bar.set(edgecolor='darkred', color='red', linewidth=3)
ax3.axhline(0,color='grey',linewidth=2)
ax3.set(title='vert')
ax4.axvline(0,color='grey',linewidth=2)
ax4.set(title='horiz')


"""4、直方圖"""
np.random.seed(19680801)
n_bins=10
x4=np.random.randn(100,3)

colors=['red','tan','lime']
#參數中density控制Y軸是概率還是數量,與返回的第一個的變量對應。
# histtype控制着直方圖的樣式,默認是 ‘bar’,即ax5;‘barstacked’ 就是疊在一起,即ax6
ax5.hist(x4,n_bins,density=True,histtype='bar',color=colors,label=colors)
ax5.legend(prop={'size':10})
ax5.set(title='bars with legend')

ax6.hist(x4,n_bins,density=True,histtype='barstacked',color=colors,label=colors)
ax6.legend(prop={'size':10})
ax6.set(title='stacked bar')

ax7.hist(x4,histtype='barstacked',rwidth=0.9) #rwidth 控制着寬度,這樣可以空出一些間隙


"""5、餅圖"""
labels='A','B','C','D'
sizes=[15,30,45,10]
explode = (0,0,0.1,0) ## 偏移,突出

ax8.pie(sizes,labels=labels,autopct='%1.1f%%',shadow=True)
ax8.axis('equal')
#autopct=%1.1f%%表示格式化百分比精確輸出,explode,突出某些塊,不同的值突出的效果不一樣。pctdistance=1.12百分比距離圓心的距離,默認是0.6.
#從90度開始畫圖,標籤,逆時針
ax9.pie(sizes,labels=labels,autopct='%1.1f%%',shadow=False,startangle=90,explode=explode,pctdistance=1.12)
ax9.axis('equal')


"""6、箱形圖"""
ax1.boxplot(data)
ax2.boxplot(data2,vert=False) #控制反向


"""7、泡泡圖"""
np.random.seed(19680801)

N = 50
x7 = np.random.rand(N)
y7 = np.random.rand(N)
colors = np.random.rand(N)
area = 5*(30 * np.random.rand(N)**2)
ax1.scatter(x7,y7,s=area,c=colors)


"""8.等高線"""
x8 = np.arange(-5,5,0.1)
y8 = np.arange(-5,5,0.1)
xx,yy = np.meshgrid(x8,y8,sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
ax3.contourf(x8,y8,z)
ax4.contour(x8,y8,z)

plt.show()

在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章