首頁 > 軟體

教你利用python的matplotlib(pyplot)繪製折線圖和柱狀圖

2022-05-14 13:01:54

前言

今天幫師兄趕在deadline之前畫論文的圖,現學現賣很是刺激,現把使用matplotlib的子庫pyplot畫折線圖和柱狀圖的程式碼記錄分享一下,方便大家參考,個人感覺pyplot真的蠻方便的,非常值得使用。

先看下官方對pyplot的描述:“Provides a MATLAB-like plotting framework.”。對,就是一個類似matlab的畫圖框架。就不多多說了,直接上程式碼吧:

一、折線圖

程式碼:

import matplotlib.pyplot as plt

#折線圖
x = [5,7,11,17,19,25]#點的橫座標
k1 = [0.8222,0.918,0.9344,0.9262,0.9371,0.9353]#線1的縱座標
k2 = [0.8988,0.9334,0.9435,0.9407,0.9453,0.9453]#線2的縱座標
plt.plot(x,k1,'s-',color = 'r',label="ATT-RLSTM")#s-:方形
plt.plot(x,k2,'o-',color = 'g',label="CNN-RLSTM")#o-:圓形
plt.xlabel("region length")#橫座標名字
plt.ylabel("accuracy")#縱座標名字
plt.legend(loc = "best")#圖例
plt.show()

執行結果:

關於上述程式碼引數的一點解釋:

plt.legend(loc=”best”) 中loc=”best”意思是自動選擇放圖例的合適位置,上圖就是放在了右下角,這個引數還有其他的設定如下:

二、柱狀圖

多個柱狀圖用顏色區分

程式碼如下:

#柱狀圖
import numpy as np
import matplotlib.pyplot as plt
ATT_LSTM = [0.8892,0.861,0.9243]
MATT_CNN = [0.8966,0.8556,0.9316]
ATT_RLSTM = [0.8867,0.8543,0.9344]
CNN_RLSTM = [0.9016,0.8636,0.9435]
#x = ['REST','LAPT','AUTO']
x = np.arange(3) #總共有幾組,就設定成幾,我們這裡有三組,所以設定為3
total_width, n = 0.8, 4    # 有多少個型別,只需更改n即可,比如這裡我們對比了四個,那麼就把n設成4
width = total_width / n
x = x - (total_width - width) / 2
plt.bar(x, ATT_LSTM, color = "r",width=width,label='ATT-LSTM ')
plt.bar(x + width, MATT_CNN, color = "y",width=width,label='MATT-CNN')
plt.bar(x + 2 * width, ATT_RLSTM , color = "c",width=width,label='ATT-RLSTM')
plt.bar(x + 3 * width, CNN_RLSTM , color = "g",width=width,label='CNN-RLSTM')
plt.xlabel("dataset")
plt.ylabel("accuracy")
plt.legend(loc = "best")
plt.xticks([0,1,2],['REST','LAPT','AUTO'])
my_y_ticks = np.arange(0.8, 0.95, 0.02)
plt.ylim((0.8, 0.95))
plt.yticks(my_y_ticks)
plt.show()

結果如下:

2. 多個柱狀圖用填充圖形(,/,*,o等)

程式碼如下:

#柱狀圖
import numpy as np
import matplotlib.pyplot as plt
ATT_LSTM = [0.8892,0.861,0.9243]
MATT_CNN = [0.8966,0.8556,0.9316]
ATT_RLSTM = [0.8867,0.8543,0.9344]
CNN_RLSTM = [0.9016,0.8636,0.9435]
#x = ['REST','LAPT','AUTO']
x = np.arange(3)

total_width, n = 0.8, 4    # 有多少個型別,只需更改n即可
width = total_width / n
x = x - (total_width - width) / 2

plt.bar(x, ATT_LSTM, color = "w",edgecolor = "k",width=width,hatch = "/",label='ATT-LSTM ')#edgecolor柱狀邊框顏色,hatch填充的內容
plt.bar(x + width, MATT_CNN, color = "w",edgecolor = "k",width=width, hatch = "+",label='MATT-CNN')
plt.bar(x + 2 * width, ATT_RLSTM , color = "w",edgecolor = "k",width=width, hatch = "*",label='ATT-RLSTM')
plt.bar(x + 3 * width, CNN_RLSTM , color = "w",edgecolor = "k",width=width, hatch = "\",label='CNN-RLSTM')
plt.xlabel("dataset")
plt.ylabel("accuracy")
plt.legend(loc = "best")
plt.xticks([0,1,2],['REST','LAPT','AUTO'])
my_y_ticks = np.arange(0.8, 0.95, 0.02)
plt.ylim((0.8, 0.95))
plt.yticks(my_y_ticks)
plt.show()

執行結果為:

這就是畫折線圖和柱狀圖的範例。

總結

到此這篇關於利用python的matplotlib(pyplot)繪製折線圖和柱狀圖的文章就介紹到這了,更多相關python pyplot畫折線圖和柱狀圖內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com