如何在直方图的 matplotlib 图例中制作线条而不是 boxes/rectangles

How to make lines instead of boxes/rectangles in a matplotlib legend of a histogram

我有一个带有图例的 (cumulatativ, step) matplotlib 直方图。但是,我对这个传说并不完全满意。我想在那里有线条而不是像我在左侧画的这些矩形(用我所有的绘画热情)

我不知道它是否有帮助,但这是我绘制此图的代码:

 hlines = [0.2, 0.4, 0.6, 0.8, 1]
for hline in hlines:
    plt.axhline(y=hline, color='lightgrey', linewidth=0.5, zorder=0.5)
plt.hist(freq_days_bw_hist1, bins=5400, density=True, cumulative=True,  color='navy', label='c1', histtype='step', linewidth=2)
plt.hist(freq_days_bw_hist2, bins=5400, density=True, cumulative=True, color='red', label='c2', histtype='step', linewidth=2)
plt.rc('legend', fontsize=16)
plt.xticks(fontsize=18)
plt.yticks(fontsize=18)
#cumulative=True,
#plt.plot(po, est_exp)
axes = plt.gca()
axes.set_xlim([0, 365])
axes.set_ylim([0, 1.1])
axes.set_xlabel('days', size=20)
axes.set_ylabel('cdfs', size=20)
plt.legend(loc='upper right')
plt.show()

提前致谢!

这应该可以解决您的问题:

from matplotlib.lines import Line2D
custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
                Line2D([0], [0], color=cmap(.5), lw=4),
                Line2D([0], [0], color=cmap(1.), lw=4)]

fig, ax = plt.subplots()
lines = ax.plot(data)
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot'])

您可以在此站点上找到一些有用的提示:https://matplotlib.org/3.1.1/gallery/text_labels_and_annotations/custom_legends.html

你的例子应该是这样的:

# rest of you code here

custom_lines = [Line2D([0], [0], color='navy', linewidth=4),
                Line2D([0], [0], color='red', linewidth=4)]

axes.legend(custom_lines, ['c1', 'c2'], loc='upper right')
plt.show()