Renewable energy in Germany

The file germany-energy-sources.txt contains data on the renewable sources of electricity produced in Germany from 1990 to 2018:

Renewable electricity generation in Germany in GWh (million kWh)
Year      Hydro    Wind      Biomass  Photovoltaics
2013     21200     49800      47800     29300
2012     21793     50670      43350     26380
2011     17671     48883      37603     19559
...

The program below plots these data as a stacked bar chart, using Matplotlib's hatch patterns to distinguish between the different sources.

import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt('germany-energy-sources.txt', skiprows=2, dtype='f8')
years = data[:,0]
n = len(years)

# GWh to TWh
data[:,1:] /= 1000

fig = plt.figure()
ax = fig.add_subplot(111)
sources = ('Hydroelectric', 'Wind', 'Biomass', 'Photovoltaics')
hatch = ['oo', '', 'xxxx', '//']
bottom = np.zeros(n)
bars = [None]*n
for i, source in enumerate(sources):
    bars[i] = ax.bar(years, bottom=bottom, height=data[:,i+1], color='w',
                    hatch=hatch[i], align='center', edgecolor='k')
    bottom += data[:,i+1]

ax.set_xticks(years)
plt.xticks(rotation=90)
ax.set_xlim(1989, 2019)
ax.set_ylabel('Renewable Electricity (TWh)')
ax.set_title('Renewable Electricity Generation in Germany, 1990-2018')
plt.legend(bars, sources, loc='best')
plt.show()

To include a legend, each bar chart object must be stored in a list, bars, which is passed to the ax.legend method with a corresponding sequence of labels, sources.

Renewable Electricity Generation in Germany, 1990-2018