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

前言

今天幫師兄趕在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畫折線圖和柱狀圖內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: