以1850-近170年的全球平均气温距基准平均气温(1961-1990年)的变化数据为例,利用matplotlibpython库,绘制数据动态可视化图。
原文博客地址:http://gaohr.win/site/blogs//-10-08-dynamic-plot-matplotlib.html
先预览一下动态效果图:
Matplotlib基础
对于Matplotlib的安装、基本使用等,网络上资源很多,此处不再过多的介绍,在此附上官网链接,足够学习使用~
* 官方主页:
* 官方示例:/gallery/index.html
* 官方API:/api/index.html
如何绘制动态图
一般情况下,利用Matplotlib绘制动态图时,通常选择使用Matplotlib的animation模块,但是该模块的函数使用比较繁琐,不易学习,开发不灵活。因此,本文介绍一种相对比较简单的办法,利用动态绘图和暂停功能来实现,具体看代码和相应的注释。
绘制动态图的函数如下:
defPlot(x, y1, y2):
'''
Create plot
:param x: 时间变量数组
:param y1: 数据数组1
:param y2: 数据数组2
:return:
'''
fig, ax = plt.subplots(figsize=(14,5))# 创建窗口和子图
plt.tick_params(labelsize=16)# 设置刻度字体
# 设置时间轴格式
fig.autofmt_xdate(rotation=30, ha='center')
dateFmt = mdate.DateFormatter('%Y')
ax.xaxis.set_major_formatter(dateFmt)
years = numpy.arange(int(x[0]),int(x[-1]) +1)
yearsDate = GetDateArr(years)# 获取年份列表
xs = [yearsDate[0], yearsDate[0
ys = [y1[0], y1[0
ys2 = [y2[0], y2[0
# 添加text
plt.text(yearsDate[-22],-0.7,'Made by GaoHR', fontsize=14, color='#1E90FF')
plt.text(yearsDate[0],-0.7,'Global temperature anomaly datasets (http://www.cru.uea.ac.uk/cru/data/temperature/)',
fontsize=14, fontfamily='Times New Roman', color='#333333')
plt.text(yearsDate[0],0.5,'The global record data were provided by Climatic Research Unit',
fontsize=14, fontfamily='Times New Roman', color='#333333')
plt.text(yearsDate[0],0.15,'The time series shows the combined global land and marine surface temperature record\n'
'from 1850 to . The base period is 1961-1990.\n'
'This year was the 4rd warmest on record.',
fontsize=14, fontfamily='Times New Roman', color='#666666')
# 设置x、y轴范围
# plt.xlim(x_min, x_max)
plt.ylim(-0.75,1)
# 设置标签、添加刻度标线
ax.set_xlabel('Year', fontsize=16, fontfamily='Times New Roman')
ax.set_ylabel('Temperature anomaly ($^o$C)', fontsize=16, fontfamily='Times New Roman')
plt.grid(True, linestyle='--', alpha=0.5)
# 动态读取数据,绘制图形
foriinrange(years[0], years[-1]):
# 更新x, y1, y2
xs[0] = xs[1
ys[0] = ys[1
ys2[0] = ys2[1
xs[1] = yearsDate[i -int(x[0
ys[1] = y1[i -int(x[0
ys2[1] = y2[i -int(x[0
ax.bar(xs, ys, width=150, color=getColor(y1[i -int(x[0])]))# 绘制条状图
ax.plot(xs, ys2, color='#555555')# 绘制曲线图
plt.legend(['Smoothed'], loc='upper left', fontsize=14)# 添加图例
plt.pause(0.1)# 设置时间间隔
plt.tight_layout()
plt.show()
补充
本示例数据(1850-全球平均气温距基准平均气温的变化数据)可以从Global temperature anomaly datasets网站上获取。
函数调用方式、数据格式,以及上述代码中用到的一些函数等,可以参见原博客:http://gaohr.win/site/blogs//-10-08-dynamic-plot-matplotlib.html
附数据静态图: