# 教你利用python的matplotlib(pyplot)绘制折线图和柱状图

## 一、折线图

```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()```