【问题标题】:How to make lines instead of boxes/rectangles in a matplotlib legend of a histogram如何在直方图的 matplotlib 图例中制作线条而不是框/矩形
【发布时间】:2021-01-28 22:00:41
【问题描述】:

我有一个带有图例的 (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()

提前致谢!

【问题讨论】:

    标签: python matplotlib legend legend-properties


    【解决方案1】:

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

    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()
    

    【讨论】:

      猜你喜欢
      • 2010-12-28
      • 2014-09-03
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 2022-11-18
      相关资源
      最近更新 更多