我想把温度绘制成一个图表,显示一整天。X轴应该是小时,y轴应该是C。
我想在这个任务中使用MatPlotLib。但也许有更好的解决办法。对当前温度进行实时更新,比较预测值和当前值。我读完了教程,但我不知道如何从预测中访问这些值。我能够接收到这些数据集并使用for循环打印它们。但是,如前所述,图形绘制方法将是很棒的。
我使用MatPlotLib尝试了一些基本的绘图,并尝试了教程。
from pyowm import OWM
import matplotlib.pyplot as plt
import numpy as np
API_key = 'XXXXXXXXXXXXXXX'
owm = OWM(API_key)
obs = owm.weather_at_place('LOCATION')
fc = owm.three_hours_forecast('LOCATION')
f = fc.get_forecast()
plt.plot(f) #How do I get the temp value out of f
plt.xlabel('h')
plt.ylabel('°C')
plt.title("Temperature")
plt.legend()
plt.show()发布于 2019-05-20 05:49:35
我很快就解析了pyOWM实例,看起来pyowm已经为openweathermap.org提供的XML/JSON提供了一些很好的语法(参见伦敦的XML数据示例)。
简单地说,fc.get_forecast()行返回一个可以迭代的预测对象(即for weather in f:),它具有作为datetime对象获得预测日期的函数,以及以开尔文为单位的温度。您现在只需要将两者都存储(例如,在简单列表times和temps中),并且可以进行绘图。请注意对fig.autofmt_xdate()的调用,它使x轴标签旋转和格式化良好。
完整代码:
from pyowm import OWM
import matplotlib.pyplot as plt
import numpy as np
API_key = 'XXXXXXXXXXXXXXX'
owm = OWM(API_key)
fc=owm.three_hours_forecast('London,GB')
f = fc.get_forecast()
times=[]
temps=[]
for weather in f:
date=weather.get_reference_time('date')
times.append(date)
t_kelvin=weather.get_temperature()['temp']## get temperature in kelvin
temps.append(t_kelvin-273.15) ## convert to celsius
print(date,t_kelvin-273.15) ## just to show what's happening
fig,ax=plt.subplots()
ax.plot(times,temps,label='forecast')
ax.set_ylabel('°C')
ax.set_title('Temperature')
ax.legend()
fig.autofmt_xdate()
plt.show()https://stackoverflow.com/questions/56211314
复制相似问题