首页 > 解决方案 > 从字典中绘制每月天气数据

问题描述

我提取了某个地点从 1978 年到 2018 年的每月天气数据,并将数据存储在字典中。

{((65.03371, 25.47957), '1978-01-01T00:00:00Z'): {'rrmon': '32.5', 'tmon': '-9.2'},
 ((65.03371, 25.47957), '1978-02-01T00:00:00Z'): {'rrmon': '11.6', 'tmon': '-14.7'},
 ((65.03371, 25.47957), '1978-03-01T00:00:00Z'): {'rrmon': '38.0', 'tmon': '-4.1'}}

字典是这样构造的,键是位置和日期的元组,并且值月降雨量和平均温度。我必须在一张图表上分别绘制每个月的温度。

例如,我如何绘制一月份的平均温度?我不知道如何在字典中只选择一个月的温度,或者我什至必须这样做?

标签: pythondictionarymatplotlib

解决方案


您可以使用分组条形图:

import matplotlib.pyplot as plt
import numpy as np
data = {((65.03371, 25.47957), '1978-01-01T00:00:00Z'): {'rrmon': '32.5', 'tmon': '-9.2'}, ((65.03371, 25.47957), '1978-02-01T00:00:00Z'): {'rrmon': '11.6', 'tmon': '-14.7'},((65.03371, 25.47957), '1978-03-01T00:00:00Z'): {'rrmon': '38.0', 'tmon': '-4.1'}}
l, d = zip(*[[a.split('T')[0], [float(b['rrmon']), float(b['tmon'])]] for (_, a), b in data.items()])
r, t = zip(*d)
x, width = np.arange(len(l)), 0.35
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, r, width, label='rrmon')
rects2 = ax.bar(x + width/2, t, width, label='tmon')
ax.set_xticks(x)
ax.set_xticklabels(l)
ax.legend()
fig.tight_layout()
plt.show()

在此处输入图像描述


推荐阅读