用matplotlib绘制简单的折线图
首先先导入matplotlib模块和numpy模块
import matplotlib.pyplot as plt
import numpy as np
导入模块后就开始创建代表画布的Figure累的对象fig,然后在画布fig上添加坐标系风格的绘图区域ax
fig = plt.figure(figsize=(10,11))
ax = fig.add_subplot(111)
然后加个标题,导入数据,绘制图表。
ax.set_title('某市未来15天气温')
x = np.arange(4,19)
y_max = np.array([32, 33, 34, 34, 33, 31, 30, 29, 30, 29, 26, 23, 21, 25, 31])
y_min = np.array([19, 19, 20, 22, 22, 21, 22, 16, 18, 18, 17, 14, 15, 16, 16])
y_med = (y_max+y_min)/2
ax.plot(x, y_max)
ax.plot(x, y_med, 'r--')
ax.plot(x, y_min)
加个图例,然后展示图表
ax.legend(['最高温度','中间温度', '最低温度'], shadow=True, fancybox=True)
plt.show()
这就是做完后的效果展示图。
柱形图
代码如下:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus']=False
fig = plt.figure(figsize=(6,4))
ax = fig.add_subplot(111)
ax.set_title('柱形数据对比图')
x = np.arange(1, 8)
y = np.array([10770, 16780, 24440, 30920, 37670, 48200, 57270])
y2 = np.array([9780, 16581, 25535, 29440, 40030, 47046, 59615])
ax.bar(x, y, tick_label=["FY2013", "FY2014", "FY2015", "FY2016", "FY2017", "FY2018", "FY2019"], width=0.3, color='orange')
ax.bar(x+0.3, y2,width=0.3, color='red')
plt.show()
成品展示:
堆积图
代码如下:
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus']=False
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
x = np.arange(1, 13)
y_a = ([192, 215, 245, 222, 200, 236, 201, 253, 236, 200, 266, 290])
y_b = ([203, 236, 200, 236, 269, 216, 298, 333, 301, 349, 360, 368])
y_c = ([185, 205, 226, 199, 238, 200, 250, 209, 246, 219, 253, 288])
ax.stackplot(x, y_a, y_b, y_c)
plt.show()
成品展示: