使用python的matplotlib(pyplot)画折线图和柱状图
·
使用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()
运行结果为:
这就是画折线图和柱状图的示例,有问题欢迎大家留言交流。
更多推荐
已为社区贡献2条内容
所有评论(0)