Python 如何使用直方图的替代图例处理程序

Python 如何使用直方图的替代图例处理程序,python,matplotlib,legend,Python,Matplotlib,Legend,我有一个图,它覆盖了一个pdf图和两个“阶梯”直方图。图例显示一条直线和两个矩形。有没有办法将两个直方图的图例处理程序更改为同时显示线条?一些示例代码是: x = np.linspace(0,2.5,1000) plt.xlim((0,2.5)) plt.ylim((0,2.5)) plt.plot(x,rv.pdf(x),'k-.',label='pdf') hist(series1,125,color='k',normed=1,histtype='step',label='hist 1',l

我有一个图,它覆盖了一个pdf图和两个“阶梯”直方图。图例显示一条直线和两个矩形。有没有办法将两个直方图的图例处理程序更改为同时显示线条?一些示例代码是:

x = np.linspace(0,2.5,1000)
plt.xlim((0,2.5))
plt.ylim((0,2.5))
plt.plot(x,rv.pdf(x),'k-.',label='pdf')
hist(series1,125,color='k',normed=1,histtype='step',label='hist 1',linestyle='dashed')
hist(series2,125,color='k',normed=1,histtype='step',label='hist 2')
plt.legend(loc='best')

rv是一个scipy.stats随机变量。

您可以使用与直方图相同的格式绘制线条,并使用这些线条创建图例:

p1, = plt.plot(rv,'k-.',label='pdf')
plt.hist(series1,125,color='k',normed=1,histtype='step',label='hist 1',linestyle='dashed')
plt.hist(series2,125,color='k',normed=1,histtype='step',label='hist 2')

# plot lines that have the same formating as the histograms
p2, = plt.plot([0,0], label='hist 1',linestyle='dashed')
p3, = plt.plot([0,0],label='hist 2')

# create the legend
plt.legend([p1, p2, p3], ['pdf', 'hist 1', 'hist2'], loc='best')

# make the lines used in the legend invisible. 
p2.set_visible(False)
p3.set_visible(False)