Plot monthly and yearly trends
Like we saw in Chapter 2, when the index of a DataFrame is of the datetime
type, it is possible to directly extract the day, month or year of each date in the index. As a reminder, you can extract the year of each date in the index using the .index.year
attribute. You can then use the .groupby()
and .mean()
methods to compute the mean annual value of each time series in your DataFrame:
index_year = df.index.year
df_by_year = df.groupby(index_year).mean()
You will now apply what you have learned to display the aggregate mean values of each time series in the jobs
DataFrame.
This exercise is part of the course
Visualizing Time Series Data in Python
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Extract the month from the index of jobs
index_month = ____.____.____
# Compute the mean unemployment rate for each month
jobs_by_month = ____.____(____).____()
# Plot the mean unemployment rate for each month
ax = ____.plot(fontsize=6, linewidth=1)
# Set axis labels and legend
ax.set_xlabel('Month', fontsize=10)
ax.set_ylabel('Mean unemployment rate', fontsize=10)
ax.legend(bbox_to_anchor=(0.8, 0.6), fontsize=10)
plt.show()