Matplotlib - show legend for .plot and .bar

Viewed 134

The code below

import numpy as np
import matplotlib.pyplot as plt

x = [1,2,3,4,5]
y = np.array([0.1,0.5,0.4,0.3,0.4])
p = [0.6,0.3,0.15,0.1,0.5]

f, axes = plt.subplots(1,2,figsize=(20,4))   

axes[0].plot(x,y)
axes[0].plot(x,y+0.05)
axes[0].bar(x,p,color="r",alpha=0.2)
axes[1].plot(x,y)
axes[1].plot(x,y+0.05)
axes[1].bar(x,p,color="r",alpha=0.2)

aliases = ["data1","data2","probabiity"]

handles = axes[1].get_lines()
f.legend(handles, aliases, loc='upper center', ncol=len(aliases),  fontsize=10, bbox_to_anchor=(0.5, 1))
plt.savefig("temp.pdf")

produces the following figure. It only shows the legend data1 and data2 for the line plots but the legend for the bar chart is empty. How can I have matplotlib include the bar chart in the same legend?

enter image description here

1 Answers
Related