一、基础绘图库:matplotlib.pyplot
1、简单画图:二次曲线
1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 if __name__ == ‘__main__‘: 5 x1 = np.linspace(-3, 3, 15) 6 y1 = [d**2 for d in x1] 7 # 画图 8 plt.plot(x1, y1) 9 x2 = [] 10 y2 = [] 11 for i, data in enumerate(y1): 12 if data >= 4: 13 x = x1[i] 14 y = data 15 text = "(%d, %d)" % (x, y) 16 # 给图片添加标注,这里的index实际是x坐标,data为y坐标, text为显示的文本内容 17 plt.text(x, y, text, color = ‘green‘) 18 x2.append(x) 19 y2.append(y) 20 plt.plot(x2, y2, ‘o‘, color=‘green‘) 21 plt.show()
绘图如下:
- 给图片增加标注: plt.text(x, y, text, color = ‘green‘)
- 画图时指定画图的格式,默认为直线,‘o’表示使用圆点:plt.plot(x2, y2, ‘o‘, color=‘green‘)
2、指定x轴为日期的画图:
1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 if __name__ == ‘__main__‘: 5 x1 = np.linspace(1, 15, 15) 6 y1 = [(x**2/40 + x*(0.3**x) + x/20) for x in x1] 7 # 画图 8 fig, ax = plt.subplots() 9 ax.plot(x1, y1) 10 x2 = [] 11 y2 = [] 12 for i, data in enumerate(y1): 13 if i % 3 ==0: 14 x = x1[i] 15 y = data 16 text = "(%d, %f)" % (x, y) 17 # 给图片添加标注,这里的index实际是x坐标,data为y坐标, text为显示的文本内容 18 plt.text(x, y, text, color = ‘green‘) 19 x2.append(x) 20 y2.append(y) 21 plt.plot(x2, y2, ‘o‘, color=‘green‘) 22 23 # 指定x轴和y轴的的名称 24 plt.xlabel("date") 25 plt.ylabel("value") 26 # xticks指定了在坐标轴上哪些位置显示label 27 xticks = x1[0::3] 28 # xticklabels指定了label的具体内容,在这里就是日期 29 xticklabels = [‘2016-03-0‘+str((n-1)*3+1) for n in range(1,len(xticks)+1)] 30 ax.set_xticks(xticks) 31 ax.set_xticklabels(xticklabels, rotation=15) 32 plt.show()
ViewCode: 添加x轴显示文本
绘图如下:
如何设置x轴的显示文本内容:
1 # xticks指定了在坐标轴上哪些位置显示label 2 xticks = x1[0::3] 3 # xticklabels指定了label的具体内容,在这里就是日期 4 xticklabels = [‘2016-03-0‘+str((n-1)*3+1) for n in range(1,len(xticks)+1)] 5 ax.set_xticks(xticks) 6 ax.set_xticklabels(xticklabels, rotation=15)
时间: 2024-10-31 22:18:03