How can I simultaneously label a histogram and a function?

Viewed 34

Here's part of the plot I'm working on: (using Python)

enter image description here

It consists of a histogram and a function. Here's the code for plotting the two items:

expc = plt.plot(x,Yt,color = 'darkorange')   
hist = plt.bar(spec.keys(), spec.values(), width=np.abs((rang2-rang1)/L), color='darkviolet',alpha = 0.7) 
plt.legend([expc, hist],['Expected','Histogram from qasm'])

I want to simultaneously label them, but it only shows one of the legends. I also got an error message:

UserWarning: Legend does not support xxx instances. A proxy artist may be used instead.

What should I do to label both items? Thanks a lot:)

2 Answers

add a comma after expc like so

expc, = plt.plot(x,Yt,color = 'darkorange')   
hist = plt.bar(spec.keys(), spec.values(), width=np.abs((rang2-rang1)/L), color='darkviolet',alpha = 0.7) 
plt.legend([expc, hist],['Expected','Histogram from qasm'])

You should pass the kwarg label="your_legend" to each data series, as in here:

import matplotlib.pyplot as plt
months = ["March", "April", "May", "June", "July", "August"]
cases = [1000, 2000, 5000, 8000, 15000, 6000]
hosp = [n*0.1 for n in cases]

plt.bar(months, cases, width=0.5, color="orange", label="All cases")
plt.bar(months, hosp, width=0.5, color="blue", label="Hospitalizations")
plt.legend()
plt.show()

enter image description here

Related