Search code examples
pythonmatplotliblegendlegend-properties

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


i have a (cumulatativ, step) matplotlib histogram plot with a legend. However, I am not totally happy with the legend. I would like to have lines in there instead of these rectangles like i drew it (with all my paint passion) on the left side I want to have a legend like the left one

I don't know if its help, but here is my code to draw this plot:

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

Thanks in advance!


Solution

  • This should solve you problem:

    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'])
    

    You can find some useful tips on this site: https://matplotlib.org/3.1.1/gallery/text_labels_and_annotations/custom_legends.html enter image description here

    Your example should be something like this:

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