ptyhon之matplotlib學習

matplotlib是python中最常用的可視工具之一,可以非常方便地創建海量類型的2D圖表和一些基本的3D圖表。

matplotlib能夠創建多數類型的圖表,如條形圖、散點圖、餅圖、堆疊圖,3D圖和地圖圖表

一、2D圖表

       最基本的模塊是pyplot

    (1)、基本圖例、標題和標籤


import matplotlib as mpl
import matplotlib.pyplot as  plt
#設置字體大小必須放在代碼前面
mpl.rcParams['xtick.labelsize'] = 24#通過rcParams設置全局橫縱字體大小
plt.rcParams['ytick.labelsize'] = 24 #通過plt.rcParams設置局部衡中字體的大小
plt.plot([1, 2, 3], [4, 5, 6], label='First Line')plt.plot([1, 2, 3],[10, 14, 12], label='Second Line')plt.xlabel('X')plt.ylabel('Y')plt.title('matplotlib study')#創建標題plt.legend()#生成默認圖例plt.show()

顯示結果:


       (2)、條形圖和直方圖

plt.figure('data')
plt.bar([1, 5, 7, 8], [2, 3, 4, 5], label='one')
plt.bar([2, 3, 6, 9], [9, 4, 3, 2], label='two')
plt.xlabel('x')#x軸
plt.ylabel('y')#y軸
plt.title('Rect Study')#創建標題

plt.legend()#生成默認圖例
plt.savefig('1.png')
plt.show('asd')

         再介紹一下 plt.hist()函數

plt.figure('hist')
population_ages = [20,12,8,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48]

bins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130]

plt.hist(population_ages, bins, histtype='bar', rwidth=0.8)

plt.xlabel('x')
plt.ylabel('y')
plt.title('hist study')
plt.legend()
plt.savefig('2.png')
plt.show()

plt.hist();第一參數代表所要測試的不同階段分組數,bins代表每個10個單位進行查找第一參數中在該階段的個數,第三個參數代表呈現的形式是矩形,第四個參數是矩形在10個單位中所佔的比列,在0-1範圍中

(3) 散點圖

     用於比較兩個變量尋找相關性或分組  

#設置rcParams全局橫縱軸字體大小
mpl.rcParams['xtick.labelsize'] = 24
mpl.rcParams['ytick.labelsize'] = 24
np.random.seed(42)
# x軸的採樣點
x = np.linspace(0, 5, 100)#等差取值 在0-5之間去100個數
#通過下面曲線加上噪聲生成數據,所以模擬模型就用y了
y = 2*np.sin(x) + 0.3*x**2
y_data = y + np.random.normal(scale=0.3, size=100)
#點圖表示
plt.figure('data0')
plt.plot(x, y_data, '.')
plt.title('point study')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.savefig('3.png')
#線圖表示
plt.figure('data1')
plt.plot(x, y_data)
plt.savefig('4.png')
#點線一起表示
plt.figure('data2')
plt.plot(x, y_data, 'k', lw = 3)#’k‘線的顏色,lw表示線的寬度
# 將scatter可以更容易地生成散點圖
plt.scatter(x,y_data)
plt.savefig('5.png')
plt.show()

data0圖:

                data1圖:


data2圖:


(4) 堆疊圖

  用於顯示【部分對整體】隨時間的關係,基本類似餅圖,只是隨時間的而變化

days = [1, 2, 3, 4]
sleep = [7, 6, 12, 9]
eat = [1, 4, 9, 3]
work = [2, 4, 3, 8]
play = [3, 5, 7, 13]

plt.plot([],[],color='m', label='sleep', linewidth=5)
plt.plot([],[],color='c', label='eat', linewidth=5)
plt.plot([],[],color='r', label='work', linewidth=5)
plt.plot([],[],color='k', label='play', linewidth=5)

plt.stackplot(days, sleep,eat,work,play, colors=['m', 'c', 'r', 'k'])

plt.xlabel('x')
plt.ylabel('y')
plt.title('dui die study')
plt.legend()
plt.savefig('6.png')
plt.show()

圖:


(5)餅圖

用於顯示部分對整體的情況,通常以%維單位,matplotlib會處理切片大小以及一切事情,我們只需要提供數值

slices = [7, 3, 10, 4]
actives = ['sleep', 'eat', 'work', 'play']
cols = ['c', 'm', 'r', 'b']
#slices每個部分的大小,lables 每個分相對的顏色,startangle起始角度,逆時針的,shadow是陰影,explode是拉出的切片,autopct是將百分比放在圖表上面
plt.pie(slices, labels=actives, startangle=90, shadow=True, explode=(0,0.1,0,0), autopct='%1.1f%%')#plt.xlabel('x')#plt.ylabel('y')plt.title('bing study')plt.savefig('7.png')plt.show()

(6)柱狀圖和餅圖綜合示例

speed ={'dog':(78,'c'), 'cat':(45,'r'), 'cheetah':(100,'b')}
fig = plt.figure('rectangle')
ax = fig.add_subplot(121)#在整張圖上加入一個子圖,121是在1行2列的子圖中的第一張
ax.set_title('runing-speed')
xticks = np.arange(3)#生成x軸每個元素的位置
bar_width = 0.5#柱的寬度
anmals = speed.keys()
speeds = [x[0] for x in speed.values()]#奔跑速度
colors = [x[1] for x in speed.values()]#對應顏色
#畫主圖,橫軸是動物標籤的位置,縱軸是速度,定義柱的寬度,同時設置柱的邊緣爲透明的
bars = ax.bar(xticks,speeds,width = bar_width,edgecolor='none')
#設置y的標題
ax.set_ylabel('Speed(km/h)')
ax.set_xticklabels(xticks+bar_width/2)
ax.set_xticklabels(anmals)
ax.set_xlim([bar_width/2-0.5, 3-bar_width/2])
ax.set_ylim([0,125])


ax = fig.add_subplot(122)
ax.set_title("pie chart")

labels = ['{}\n km/h'.format(a, s) for a, s in zip(anmals, speeds)]
ax.pie(speeds, labels=labels, colors=colors)
plt.axis()


plt.savefig('8.png')





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