<jupyter_start><jupyter_text>More advanced plotting with Pandas/Matplotlib```{attention}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 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.![Subplot example in Matplotlib](img/subplots.png)  The dataIn this part of the lesson we'll continue working with our weather observation data from the Helsinki-Vantaa airport [downloaded from NOAA](https://www7.ncdc.noaa.gov/CDO/cdopoemain.cmd?datasetabbv=DS3505&countryabbv=&georegionabbv=&resolution=40).  Getting startedLet's start again by importing the libraries we'll need.<jupyter_code>import pandas as pd
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>Loading the dataNow we'll load the data just as we did in the first part of the lesson: - Set whitespace as delimiter- Specify no data values- Specify a subset of columns- Parse `'YR--MODAHRMN'` column as a datetime indexReading in the data might take a few moments.<jupyter_code>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')
print("Number of rows:", len(data))<jupyter_output><empty_output><jupyter_text>We are dealing with a relatively large data set.Let's have a closer look at the time first rows of data:<jupyter_code>data.head()<jupyter_output><empty_output><jupyter_text>Let's rename the `'TEMP'` column as `TEMP_F`, since we'll later convert our temperatures from Fahrenheit to Celsius.<jupyter_code>new_names = {'TEMP':'TEMP_F'}
data = data.rename(columns=new_names)<jupyter_output><empty_output><jupyter_text>Check again the first rows of data to confirm successful renaming:<jupyter_code>data.head()<jupyter_output><empty_output><jupyter_text>Preparing the dataFirst, we have to deal with no data values. Let's check how many no data values we have:<jupyter_code>print('Number of no data values per column: ')
print(data.isna().sum())<jupyter_output><empty_output><jupyter_text>So, we have 3579 missing values in the TEMP_F column. Let's get rid of those. We need not worry about the no data values in `'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:<jupyter_code>data.dropna(subset=['TEMP_F'], inplace=True)
print("Number of rows after removing no data values:", len(data))<jupyter_output><empty_output><jupyter_text>That's better.  Check your understandingWhat 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)?<jupyter_code># After removing all no data values we are left with only a fraction of the original data.
# Note! Here we are not applying .dropna() "inplace" 
#       so we are not making any permanent changes to our dataframe.
len(data.dropna())
# We continue with the dataframe where rows with missing TEMP_F values have been removed
len(data)<jupyter_output><empty_output><jupyter_text>Converting temperatures to CelsiusNow that we have loaded our data, we can convert the values of temperature in Fahrenheit to Celsius, like we have in earlier lessons.<jupyter_code>data["TEMP_C"] = (data["TEMP_F"] - 32.0) / 1.8<jupyter_output><empty_output><jupyter_text>Let's check how our dataframe looks like at this point:<jupyter_code>data.head()<jupyter_output><empty_output><jupyter_text>Using subplotsLet'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.  Extracting seasonal temperaturesLet's now select data from different seasons of the year in 2012/2013:- Winter (December 2012 - February 2013)- Spring (March 2013 - May 2013)- Summer (June 2013 - August 2013)- Autumn (Septempber 2013 - November 2013)<jupyter_code>winter = data.loc[(data.index >= '201212010000') & (data.index < '201303010000')]
winter_temps = winter['TEMP_C']

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']<jupyter_output><empty_output><jupyter_text>Now we can plot our data to see how the different seasons look separately.<jupyter_code>ax1 = winter_temps.plot()
ax2 = spring_temps.plot()
ax3 = summer_temps.plot()
ax4 = autumn_temps.plot()<jupyter_output><empty_output><jupyter_text>OK, so from these plots we can already see that the temperatures in different 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 different 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 of the different seasons. Finding data boundsLet'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.<jupyter_code># Find lower limit for y-axis
min_temp = min(winter_temps.min(), spring_temps.min(), summer_temps.min(), autumn_temps.min())
min_temp = min_temp - 5.0

# 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("Min:", min_temp, "Max:", max_temp)<jupyter_output><empty_output><jupyter_text>We can now use this temperature range to standardize the y-axis scale of our plot. Creating our first set of subplotsLet'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 that takes the `width` and `height` values (in inches) as input.<jupyter_code>fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(12,8));
axs<jupyter_output><empty_output><jupyter_text>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 own variables so it is easier to work with them.<jupyter_code>ax11 = axs[0][0]
ax12 = axs[0][1]
ax21 = axs[1][0]
ax22 = axs[1][1]<jupyter_output><empty_output><jupyter_text>Now we have four different axis variables for different panels in our figure.Next we can use them to plot the seasonal data into them.Let's first plot the seasons and give different colors for the lines, and specify the *y*-scale limits to be the same with all subplots.- `c` parameter changes the color of the line.You can find an extensive list of possible colors and RGB-color codes from [this link](http://www.rapidtables.com/web/color/RGB_Color.htm).- `lw` parameter controls the width of the line.- `ylim` parameter controls the y-axis limits<jupyter_code># 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])
spring_temps.plot(ax=ax12, c='orange', lw=line_width, ylim=[min_temp, max_temp])
summer_temps.plot(ax=ax21, c='green', lw=line_width, ylim=[min_temp, max_temp])
autumn_temps.plot(ax=ax22, c='brown', lw=line_width, ylim=[min_temp, max_temp])

# Display figure
fig<jupyter_output><empty_output><jupyter_text>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.<jupyter_code># 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]<jupyter_output><empty_output><jupyter_text>Now, we'll add our seasonal temperatures to the plot commands for each time period.<jupyter_code># 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<jupyter_output><empty_output><jupyter_text>Not bad.  Check your understading Visualize winter and summer temperatures in a 1x2 panel figure.Save the figure as a .png file.<jupyter_code># Two subplots side-by-side
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(12,4))

# Set plot line width
line_width = 1.5

# Plot data
winter_temps.plot(ax=axs[0], c='blue', lw=line_width, 
                  ylim=[min_temp, max_temp], grid=True)
summer_temps.plot(ax=axs[1], c='green', lw=line_width,
                  ylim=[min_temp, max_temp], grid=True)

# Set figure title
fig.suptitle('2012-2013 Winter and summer temperature observations - Helsinki-Vantaa airport')

# Rotate the x-axis labels so they don't overlap
plt.setp(axs[0].xaxis.get_majorticklabels(), rotation=20)
plt.setp(axs[1].xaxis.get_majorticklabels(), rotation=20)

# Axis labels
axs[0].set_xlabel('Date')
axs[1].set_xlabel('Date')
axs[0].set_ylabel('Temperature [°C]')
axs[1].set_ylabel('Temperature [°C]')

# Season label text
axs[0].text(pd.to_datetime('20130215'), -25, 'Winter')
axs[1].text(pd.to_datetime('20130815'), -25, 'Summer')

plt.savefig("HelsinkiVantaa_WinterSummer_2012-2013.png")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11185923332435586, 'fraction_numerical': 0.03384504892719275, 'mean_word_length': 5.52989449003517, 'pattern_counts': {'":': 0, '<': 81, '<?xml version=': 0, '>': 81, 'https://': 1, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '19', 'dir': 'jupyter-structured-clean-dedup', 'id': '636127', 'license': 'MIT', 'n_tokens_mistral': 3949, 'n_tokens_neox': 3610, 'n_words': 1199, 'path': 'Python/2. Python Basics (cont.)/3. Pandas/Notebooks/Pandas - Books, Problem Sets, Lessons, and Solutions/Additional Notebooks/Pandas-Complete-Introduction-Thorough/2. Additional Examples - Misc/L4/advanced-plotting.ipynb', 'repo_name': 'okara83/Becoming-a-Data-Scientist', 'size': '11139'}