Making stacked plots

In this recipe, we will show you how to produce a stacked plot. Stacked plots are used when plotting a quantity which can be represented as the sum of several contributions. A stacked plot will allow us to represent not only the overall trend but also the trend of each individual components contributing to the total quantity.

Getting ready

We will consider the world's energy production as our total quantity and will represent the detailed break down in different energy sourced. We will represent the evolution of energy production type from 1973 to 2014. This data is contained in the file ch03-energy-production.csv. The data has been taken from http://www.eia.gov/totalenergy/data/monthly/ and reshaped for the need of the recipe.

How to do it...

Here is the code to produce the stacked plot displayed further:

import pandas as pd
import matplotlib.pyplot as plt

# We load the data with pandas.
df = pd.read_csv('ch03-energy-production.csv')

# We give names for the columns that we want to load. Different types of energy have been ordered by total production values).
columns = ['Coal', 'Natural Gas (Dry)', 'Crude Oil', 'Nuclear Electric Power',
 'Biomass Energy', 'Hydroelectric Power', 'Natural Gas Plant Liquids',
 'Wind Energy', 'Geothermal Energy', 'Solar/PV Energy']

# We define some specific colors to plot each type of energy produced.
colors = ['darkslategray', 'powderblue', 'darkmagenta', 'lightgreen', 'sienna',
'royalblue', 'mistyrose', 'lavender', 'tomato', 'gold']

# Let's create the figure.
plt.figure(figsize = (12,8))
polys = plt.stackplot(df['Year'], df[columns].values.T, colors = colors)

# The legend is not yet supported with stackplot. We will add it manually.
rectangles= []
for poly in polys:
rectangles.append(plt.Rectangle((0, 0), 1, 1, fc=poly.get_facecolor()[0]))
legend = plt.legend(rectangles, columns, loc = 3)
frame = legend.get_frame()
frame.set_color('white')

# We add some information to the plot.
plt.title('Primary Energy Production by Source', fontsize = 16)
plt.xlabel('Year', fontsize = 16)
plt.ylabel('Production (Quad BTU)', fontsize = 16)
plt.xticks(fontsize = 16)
plt.yticks(fontsize = 16)
plt.xlim(1973,2014)

# Finally we show the figure.
plt.show()

Here is the plot we obtain:

How to do it...

At a glance, we can see that the world's energy production is constantly increasing and has entered a faster growing phase since 2005. We can also analyze the evolution of each type of energy. Coal production is slowly decreasing while natural gas and crude oil productions are increasing. Nuclear production has also started to decrease. At the top of the stacked plot (which is more visible by zooming), we can see that renewable energies are still forming a negligible part of the global world's production. The stacked plot was the perfect tool to represent this dataset.

How it works...

The command stackplot() works just like the plot() command but can accept a multidimensional array as a second input. This array's first dimension is the number of filled areas to plot while the second dimension is the same as the first input array. In our case, the shape of df['Year'] is (42,), while the shape of df[columns].values.T is (10,42). Note that we use the transpose operator T in order to have the second array in the right format. stackplot() creates a list of polygons that we store in the variable polys.

The legend is not yet supported with stacked plots. We therefore use the commands plt.Rectangle() to create the legend's rectangles. Each rectangle's colors is specified using poly.get_facecolor()[0], where poly is an element of the list of polygons created by the stackplot() command.

Plotting the legend is then done simply using the command legend() with the rectangles as first arguments and the names of each corresponding type of energy source as second arguments. The third argument is used to specify the location of the legend. We set the background of the legend to white by first using the method get_frame() of the object legend, and then setting it's color to white with the frame's set_color() method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.30.19