Kai
Kai

Reputation: 67

Plotting weather forecast using matplotlib

I want to plot the temperature into a graph, showing the whole day. The x-axis should be the hours and the y-axis °C.

I would like to use MatPlotLib for this task. But maybe there is a better solution for this. In terms of a real time update of the current temperature to compare the forecast and the current values. I went through the tutorial, but I can't figure out, how to access these values from the forecast. I was able to receive those data sets and print them using a for loop. But as already mentioned a graphical plotting method would be great.

I tried some basic plotting using MatPlotLib and tried the tutorials.

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()

Upvotes: 0

Views: 3114

Answers (1)

Asmus
Asmus

Reputation: 5247

I've quickly parsed the pyOWM examples, and it looks like pyowm is already providing some nice syntax for the XML/JSON that is provided by openweathermap.org (see example XML data for London).

Simply put, the fc.get_forecast() line returns a forecast object which can be iterated over (i.e. for weather in f:), and which has functions to get the forecast date as a datetime object, and the temperature in Kelvin. You now only need to store both (e.g. in simple lists times and temps) and are ready to plot. Note the call to fig.autofmt_xdate() which makes the x-axis labels rotate and format nicely.

complete code:

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()

Upvotes: 1

Related Questions