Finnish university students are encouraged to use the CSC Notebooks platform.
Others can follow the lesson and fill in their student notebooks using Binder.
At this point you should know the basics of making plots with pandas and the Matplotlib module. Now we will expand on our basic plotting skills to learn how to create more advanced plots. In this part, we will show how to visualize data using pandas/Matplotlib and create plots such as the one below.
In this part of the lesson we'll continue working with our weather observation data from the Helsinki-Vantaa airport downloaded from NOAA.
Let's start again by importing the libraries we'll need.
import pandas as pd
import matplotlib.pyplot as plt
Now we'll load the data just as we did in the first part of the lesson:
'YR--MODAHRMN'
column as a datetime indexReading in the data might take a few moments.
fp = r"data/029740.txt"
data = pd.read_csv(fp, delim_whitespace=True,
na_values=['*', '**', '***', '****', '*****', '******'],
usecols=['YR--MODAHRMN', 'TEMP', 'MAX', 'MIN'],
parse_dates=['YR--MODAHRMN'], index_col='YR--MODAHRMN')
As you can see, we are dealing with a relatively large data set.
Let's have a closer look at the time first rows of data:
Let's rename the 'TEMP'
column as TEMP_F
, since we'll later convert our temperatures from Fahrenheit to Celsius.
new_names = {'TEMP':'TEMP_F'}
data = data.rename(columns=new_names)
Check again the first rows of data to confirm successful renaming:
First, we have to deal with no data values. Let's check how many no data values we have:
So, we have 1644 missing values in the TEMP_F column. Let's get rid of those. We need not worry about the no data values in the 'MAX'
and 'MIN'
columns since we won't be using them for plotting.
We can remove rows from our DataFrame where 'TEMP_F'
is missing values using the dropna()
method, as shown below:
That's better.
What would happen if we removed all rows with any no data values from our data (also considering no data values in the MAX
and MIN
columns)?
# Calculate the number of rows after removing all no data values
# Note: Do not apply .dropna() with the "inplace" parameter!
# Calculate the number of rows without removing all rows containing NA values
Now that we have loaded our data, we can convert the values of temperature in Fahrenheit to Celsius, like we have in earlier lessons.
Let's check how our dataframe looks like at this point:
Let's continue working with the weather data and learn how to use subplots. Subplots are figures where you have multiple plots in different panels of the same figure, as was shown at the start of the lesson.
Let's now select data from different seasons of the year in 2012/2013:
# Type in the example for winter
spring = data.loc[(data.index >= '201303010000') & (data.index < '201306010000')]
spring_temps = spring['TEMP_C']
summer = data.loc[(data.index >= '201306010000') & (data.index < '201309010000')]
summer_temps = summer['TEMP_C']
autumn = data.loc[(data.index >= '201309010000') & (data.index < '201312010000')]
autumn_temps = autumn['TEMP_C']
Now we can plot our data to see how the different seasons look separately.
# Example plot for winter
ax2 = spring_temps.plot()
ax3 = summer_temps.plot()
ax4 = autumn_temps.plot()
OK, so from these plots we can already see that the temperatures the four seasons are quite different, which is rather obvious of course. It is important to also notice that the scale of the y-axis changes in these four plots. If we would like to compare different seasons to each other we need to make sure that the temperature scale is similar in the plots for each season.
Let's set our y-axis limits so that the upper limit is the maximum temperature + 5 degrees in our data (full year), and the lowest is the minimum temperature - 5 degrees.
# Find minimum seasonal temperature
# Find upper limit for y-axis
max_temp = max(winter_temps.max(), spring_temps.max(), summer_temps.max(), autumn_temps.max())
max_temp = max_temp + 5.0
# Print y-axis min, max
print(f'Min: {min_temp}, Max: {max_temp}')
We can now use this temperature range to standardize the y-axis range on our plot.
Let's now continue and see how we can plot all these different plots into the same figure. We can create a 2x2 panel for our visualization using Matplotlib’s subplots()
function where we specify how many rows and columns we want to have in our figure. We can also specify the size of our figure with figsize
parameter as we have seen earlier with pandas. As a reminder, figsize
takes the width
and height
values (in inches) as inputs.
We can see that as a result we have now a list containing two nested lists where the first one contains the axis for column 1 and 2 on row 1 and the second list contains the axis for columns 1 and 2 for row 2.
We can parse these axes into their own variables so it is easier to work with them.
ax11 = axs[0][0]
ax12 = axs[0][1]
ax21 = axs[1][0]
ax22 = axs[1][1]
Now we have four axis variables for the different panels in our figure. Next we can use them to plot the seasonal data. Let's begin by plotting the seasons, and give different colors for the lines and specify the y-axis range to be the same for all subplots. We can do this using what we know and some parameters below:
c
parameter changes the color of the line. Matplotlib has a large list of named colors you can consult to customize your color scheme.lw
parameter controls the width of the linesylim
parameter controls the y-axis range# Set the plot line width
line_width = 1.5
# Plot data
# Winter
# Spring
spring_temps.plot(ax=ax12, c='orange', lw=line_width, ylim=[min_temp, max_temp])
# Summer
summer_temps.plot(ax=ax21, c='green', lw=line_width, ylim=[min_temp, max_temp])
# Autumn
autumn_temps.plot(ax=ax22, c='brown', lw=line_width, ylim=[min_temp, max_temp])
# Display the figure
fig
Great, now we have all the plots in same figure! However, we can see that there are some problems with our x-axis labels and a few missing items we can add. Let's do that below.
# Create the new figure and subplots
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(12,8))
# Rename the axes for ease of use
ax11 = axs[0][0]
ax12 = axs[0][1]
ax21 = axs[1][0]
ax22 = axs[1][1]
Now, we'll add our seasonal temperatures to the plot commands for each time period.
# Set plot line width
line_width = 1.5
# Plot data
winter_temps.plot(ax=ax11, c='blue', lw=line_width,
ylim=[min_temp, max_temp], grid=True)
spring_temps.plot(ax=ax12, c='orange', lw=line_width,
ylim=[min_temp, max_temp], grid=True)
summer_temps.plot(ax=ax21, c='green', lw=line_width,
ylim=[min_temp, max_temp], grid=True)
autumn_temps.plot(ax=ax22, c='brown', lw=line_width,
ylim=[min_temp, max_temp], grid=True)
# Set figure title
fig.suptitle('2012-2013 Seasonal temperature observations - Helsinki-Vantaa airport')
# Rotate the x-axis labels so they don't overlap
plt.setp(ax11.xaxis.get_majorticklabels(), rotation=20)
plt.setp(ax12.xaxis.get_majorticklabels(), rotation=20)
plt.setp(ax21.xaxis.get_majorticklabels(), rotation=20)
plt.setp(ax22.xaxis.get_majorticklabels(), rotation=20)
# Axis labels
ax21.set_xlabel('Date')
ax22.set_xlabel('Date')
ax11.set_ylabel('Temperature [°C]')
ax21.set_ylabel('Temperature [°C]')
# Season label text
ax11.text(pd.to_datetime('20130215'), -25, 'Winter')
ax12.text(pd.to_datetime('20130515'), -25, 'Spring')
ax21.text(pd.to_datetime('20130815'), -25, 'Summer')
ax22.text(pd.to_datetime('20131115'), -25, 'Autumn')
# Display plot
fig
Not bad.
Visualize winter and summer temperatures in a 1x2 panel figure. Save the figure as a .png file.
One cool thing about plotting using pandas/Matplotlib is that is it possible to change the overall style of your plot to one of several available plot style options very easily. Let's consider an example below using the four-panel plot we produced in this lesson.
We will start by defining the plot style, using the 'dark_background'
plot style here.
plt.style.use('dark_background')
There is no output from this command, but now when we create a plot it will use the dark_background
styling. Let's see what that looks like.
# Create the new figure and subplots
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(14,9))
# Rename the axes for ease of use
ax11 = axs[0][0]
ax12 = axs[0][1]
ax21 = axs[1][0]
ax22 = axs[1][1]
# Set plot line width
line_width = 1.5
# Plot data
winter_temps.plot(ax=ax11, c='blue', lw=line_width,
ylim=[min_temp, max_temp], grid=True)
spring_temps.plot(ax=ax12, c='orange', lw=line_width,
ylim=[min_temp, max_temp], grid=True)
summer_temps.plot(ax=ax21, c='green', lw=line_width,
ylim=[min_temp, max_temp], grid=True)
autumn_temps.plot(ax=ax22, c='brown', lw=line_width,
ylim=[min_temp, max_temp], grid=True)
# Set figure title
fig.suptitle('2012-2013 Seasonal temperature observations - Helsinki-Vantaa airport')
# Rotate the x-axis labels so they don't overlap
plt.setp(ax11.xaxis.get_majorticklabels(), rotation=20)
plt.setp(ax12.xaxis.get_majorticklabels(), rotation=20)
plt.setp(ax21.xaxis.get_majorticklabels(), rotation=20)
plt.setp(ax22.xaxis.get_majorticklabels(), rotation=20)
# Axis labels
ax21.set_xlabel('Date')
ax22.set_xlabel('Date')
ax11.set_ylabel('Temperature [°C]')
ax21.set_ylabel('Temperature [°C]')
# Season label text
ax11.text(pd.to_datetime('20130215'), -25, 'Winter')
ax12.text(pd.to_datetime('20130515'), -25, 'Spring')
ax21.text(pd.to_datetime('20130815'), -25, 'Summer')
ax22.text(pd.to_datetime('20131115'), -25, 'Autumn')
As you can see, the plot format has now changed to use the dark_background
style. You can find other plot style options in the complete list of available Matplotlib style sheets. Have fun!