Matplotlib画图例子

最近项目中需要统计一些数据并画出图表,有人说可以用excel,可是我不熟悉这东西,于是就用Python写代码的方式来处理。有时候为了一点小效果,也是看了不少别人的例子才能完成,现把代码放这里,以后自己用到的时候可以直接拷贝,也可以给别人参考。

import matplotlib
matplotlib.use(“Agg”)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator

xdisaStimeList = [‘2015-08-09’, ‘2016-03-04’, ‘2017-01-04’, ‘2018-05-10’, ‘2019-02-04’, ‘2019-09-04’]
ydisaGradeList = [3, 5, 6, 1, 2, 9]
zdisaValueList = [6.1, 1.5, 15.2, 3.5, 8.4, 20.3]
dtestValueList = [7, 8, 10, 11,29, 3] # D-axis
yDurationList = [1, 2, 5, 0, 2, 1]

fig, ax = plt.subplots()
ax2 = ax.twinx()
ax3 = ax.twinx()

ax.plot(xdisaStimeList, ydisaGradeList, ‘–ro’)
ax2.plot(xdisaStimeList, zdisaValueList, ‘-bo’)
ax3.plot(xdisaStimeList, dtestValueList, ‘-go’)

ax3.spines[“right”].set_position((“outward”, 80))

tourName=”某某景区”ax.set_title(tourName + ‘-高温热浪灾害历史记录’, fontsize=22)


ax.set_ylabel(‘灾害等级(1,2,3,…)’, color=’r’, fontsize=18)
ax.set_xlabel(‘灾害时间’, fontsize=18)
ax2.set_ylabel(‘雨量值(mm)’, color=’b’, fontsize=18)
ax3.set_ylabel(‘温度值(℃)’, color=’g’, fontsize=18)

for i,j in zip(xdisaStimeList, zdisaValueList):
ax2.annotate(str(j), xy=(i,j+0.2))
for i,j in zip(xdisaStimeList, dtestValueList):
ax3.annotate(str(j), xy=(i,j+0.2))

ax.grid()

fig.autofmt_xdate()

fig.set_size_inches(18, 10)

fig.savefig(“1.png”)

xmonthInYear = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] # X-axis, Months
ydsFrequency = [3, 1, 2, 4, 0, 1, 7, 2, 3, 9, 1, 0] # Disaster frequency in every month

fig, ax1 = plt.subplots()

ax1.plot(xmonthInYear, ydsFrequency, ‘-ro’)

ax1.set_title(tourName + ‘-暴雨洪涝灾害频率图’, fontsize=22)
ax1.set_ylabel(‘灾害发生频率’, color=’r’, fontsize=18)
ax1.set_xlabel(‘灾害月份’, fontsize=18)

x_major_locator=MultipleLocator(1)
ax1.xaxis.set_major_locator(x_major_locator)

for i,j in zip(xmonthInYear, ydsFrequency):
ax1.annotate(str(j), xy=(i,j+0.2))

ax1.grid()

fig.autofmt_xdate()
fig.set_size_inches(18, 10)

fig.savefig(‘2.png’)

fig, ax1 = plt.subplots()

ax1.plot(xdisaStimeList, yDurationList, ‘-ro’)

ax1.set_title(tourName + ‘-暴雨洪涝灾害时长图’, fontsize=22)
ax1.set_ylabel(‘灾害发生时长’, color=’r’, fontsize=18)
ax1.set_xlabel(‘灾害时间’, fontsize=18)

for i,j in zip(xdisaStimeList, yDurationList):
ax1.annotate(str(j), xy=(i,j+0.2))

x_major_locator=MultipleLocator(1)
ax1.xaxis.set_major_locator(x_major_locator)

ax1.grid()

fig.autofmt_xdate()
fig.set_size_inches(18, 10)

fig.savefig(‘3.png’)

data = [5, 20, 15, 25, 10]
labels = [1, 2, 3, 4, 5]

plt.bar(range(len(data)), data, tick_label=labels)
plt.xlabel(‘X axis’)
plt.ylabel(‘Y axis’)
plt.title(‘Test bar’)
for x, y in enumerate(data):
plt.annotate(str(y), xy=(x-0.1,y+0.2))

plt.savefig(‘bar.png’)

最终生成的图表如下所示: