利用matplotlib库中面向对象API,绘制折线图和柱形图
折线图:
#导入模块
import matplotlib.pyplot as plt
import numpy as np
#figsize:画布大小
fig = plt.figure(figsize=(2, 2))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
#准备数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 5])
x1 = np.array([1, 2, 3])
y1 = np.array([4, 5, 6])
#调用plot函数
ax1.plot(x,y,'go-')
ax2.plot(x1,y1,'r-.')
#展示图表
plt.show()
效果如下
柱形图:
使用bar()函数绘制柱形图或堆积柱形图plot(x,height,width=0.8,bottom=None,align='center',data=None,tick_label=None,xerr=None,yerr=None,error_kw=None,**kwargs)
#导入模块
import matplotlib.pyplot as plt
import numpy as np
#figsize:画布大小
fig = plt.figure(figsize=(7,5))
ax = fig.add_subplot(111)
#准备数据
x = np.arange(0,6)
y = np.array([11,9,5,7,6,10])
bar_width = 0.3
#调用bar()函数
ax.bar(x,y,tick_label=['a','b','c','d','e','f'],width=bar_width,color='orange')
#展示图表
plt.show()
#效果如下