Ebrahim Jakoet
Ebrahim Jakoet

Reputation: 417

Matplotlib legend with line and area styles

I am trying to plot a line and area graph in the same figure with a legend that displays both the line and area styles. Unfortunately the code below only produces lines and no areas in the legend.

Is it possible to get both lines and areas in the same legend? If not, can I get a second legend for the area charts on the same figure?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.abs(np.random.randn(6,4)), index=dates, columns=list('ABCD'))
f, ax = plt.subplots()
df[['A','B']].plot(ax=ax, figsize=(10,5))
df[['C','D']].plot(kind='area',ax=ax, figsize=(10,5))
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plot of line and area graphs

Upvotes: 2

Views: 1825

Answers (1)

kikocorreoso
kikocorreoso

Reputation: 4219

You can do it in the following way:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patches

# data
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.abs(np.random.randn(6,4)), 
                  index=dates, 
                  columns=list('ABCD'))

# plot
f, ax = plt.subplots()
# lines A and B
lineA, = ax.plot(df.index, df['A'], color = 'black', label = 'A')
lineB, = ax.plot(df.index, df['B'], color = 'green', label = 'B')
# stacked plots
ax.fill_between(df.index, 0, df['C'], color = 'blue',label = 'C')
ax.fill_between(df.index, df['C'], df['D'], color = 'red', label = 'D')
# Labels for both stacked plots
blue_patch = patches.Patch(color='blue', label='C')
red_patch = patches.Patch(color='red', label='D')
# legend
ax.legend(handles = [lineA, lineB, blue_patch, red_patch],
          loc='center left', bbox_to_anchor=(1, 0.5))
# show the final plot
f.show()

Have a look to the legend guide here.

Upvotes: 2

Related Questions