Matplotlib繪圖基礎

東血發表於2022-07-01

Matplotlib是資料視覺化的基礎,可以用來繪製線圖、散點圖、等高線圖、條形圖、柱狀圖、3D 圖形、甚至是圖形動畫等 matplotlib.pyplot是繪製各類視覺化圖形的命令子庫,相當於快捷方式。

1.繪製散點圖

#繪製散點圖
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,2*np.pi,100)
y=np.sin(x)+np.random.random(len(x))
#正確顯示標題中文
plt.rcParams['font.sans-serif']='SimHei'
#正確顯示座標軸負號
plt.rcParams['axes.unicode_minus']=False
plt.title('sin散點')
plt.scatter(x,y)
plt.show()

img

2.繪製折線圖

In [ ]:

#繪製折線圖
x=np.linspace(0,2*np.pi,100)
y=np.sin(x)+np.random.rand(100)
plt.scatter(x,y)
plt.plot(x,y,'r')
plt.plot(x,np.sin(x)+0.5,'g')
plt.legend(['折線','sin曲線'])
plt.show()

img

3.繪製柱狀圖

In [ ]:

#繪製柱狀圖
x=range(10)
np.random.seed(123)
y1=np.random.random(10)
y2=np.random.random(10)

plt.bar(x,y1,facecolor='r')
plt.bar(x,-y2,facecolor='g')

for i,j in zip(x,y1):
    plt.text(i,j,'%.2f'%j,ha='center',va='bottom')

for i,j in zip(x,y2):
    plt.text(i,-j,'%.2f'%j,ha='center',va='top')

plt.show()

img

4.繪製餅圖

In [ ]:

#繪製餅圖
z=np.ones(10)
plt.figure(figsize=(5,5))
plt.pie(z,autopct='%.2f%%',explode=[0.1]+[0]*9,labels=list('ABCDEFGHIJ'),labeldistance=1.1)
plt.show()

img

5.參考文章

[Matplotlib基礎知識_堅果的刻薄-CSDN部落格](https://blog.csdn.net/qq_48003414/article/details/116882379#:~:text=Matplotlib是資料視覺化的基礎,可以用來繪製線圖、散點圖、等高線圖、條形圖、柱狀圖、3D,圖形、甚至是圖形動畫等 matplotlib.pyplot是繪製各類視覺化圖形的命令子庫,相當於快捷方式。)

【創作不易,望點贊收藏,若有疑問,請留言,謝謝】

相關文章