matplotlib 实际上是一个面向对象的绘图库,它所绘制的图表元素均对应一个对象。但 matplotlib 在设计之初仿照 MATLAB,它提供了一套与 MATLAB 命令类似的 API,方便熟悉 MATLAB 的用户进行开发。matplotlib官网提供了3种API:pyplot APIobject-oriented API pylab API。
1.折线图
代码如下:
import matplotlib.pyplot as plt import numpy as np x = np.arange(19, 30) y_max = np.array([34, 35, 35, 31, 33, 33, 33, 34, 35, 35, 35]) y_min = np.array([25, 26, 27, 26, 25, 25, 26, 26, 26, 27, 26]) plt.plot(x, y_max) plt.plot(x, y_min) plt.show()
绘制成果如下:
若想更改折线图线的状态和颜色则在plt.plot(x, y_max)添加 ls='dashed',c='red' 虚线红色
也可以在plt.plot(x, y_max)加'--,r'
代码如下:
plt.plot(x, y_min,ls ='dashed',c='red') 或 plt.plot(x, y_min,'--,r')
效果如下:
2.柱状图
(1)绘制柱形图代码如下:
import matplotlib.pyplot as plt import numpy as np x = np.arange(5) y1 = np.array([10,8,7,11,13]) bar_width = 0.3 #设置宽度 plt.bar(x, y1, tick_label=['a','b','c','d','e'],width = bar_width) plt.show()
绘制成果如下:
当有多组数据做比较时,如一个商城同一商品a再第一季度的销售量和第二季度的销售量做对比时可以使用多组柱状图来更好的呈现出两季度的差异,而多组柱形图是在柱形图的基础上添加多一组数据。
(2)多组柱形图代码如下
import matplotlib.pyplot as plt import numpy as np x = np.arange(5) y1 = np.array([10,8,7,11,13]) y2 = np.array([9,6,5,10,12]) bar_width = 0.3 #设置宽度 plt.bar(x, y1, tick_label=['a','b','c','d','e'],width = bar_width) plt.bar(x+bar_width,y2,width = bar_width) #若x不+bar_width就会两柱重叠 plt.show()
绘制成果如下:
(3)堆积柱形图代码如下:
x = np.arange(5) y1 = np.array([10,8,7,11,13]) y2 = np.array([9,6,5,10,12]) bar_width = 0.3 plt.bar(x, y1, tick_label=['a','b','c','d','e'],width = bar_width) plt.bar(x,y2,bottom=y1,width = bar_width) plt.show()
(4)误差棒:
x = np.arange(5) y1 = np.array([10,8,7,11,13]) y2 = np.array([9,6,5,10,12]) bar_width = 0.3 error = [2,2.5,3,1,4] #误差棒数据 plt.bar(x, y1, tick_label=['a','b','c','d','e'],width = bar_width) plt.bar(x,y2,bottom=y1,width = bar_width,yerr = error) plt.show()
3.内容补充
颜色: