Legend not showing up in Matplotlib stacked area plot

后端 未结 4 2043
借酒劲吻你
借酒劲吻你 2020-12-13 14:59

I am creating a stacked line/area plot using plt.fill_between() method of the pyplot, and after trying so many things I am still not able to figure why it is not displaying

相关标签:
4条回答
  • 2020-12-13 15:02

    Only to give an update about this matter as I as looking for it. At 2016, PolyCollection already provide support to the label attribute as you can see:

    https://github.com/matplotlib/matplotlib/pull/3303#event-182205203

    0 讨论(0)
  • 2020-12-13 15:05

    Another, arguably easier, technique is to plot an empty data set, and use it's legend entry:

    plt.plot([], [], color='green', linewidth=10)
    plt.plot([], [], color='red', linewidth=10)
    

    This works well if you have other data labels for the legend, too:

    enter image description here

    0 讨论(0)
  • 2020-12-13 15:15

    gcalmettes's answer was a helpful start, but I wanted my legend to pick up the colors that the stackplot had automatically assigned. Here's how I did it:

    polys = pyplot.stackplot(x, y)
    legendProxies = []
    for poly in polys:
        legendProxies.append(pyplot.Rectangle((0, 0), 1, 1, fc=poly.get_facecolor()[0]))
    
    0 讨论(0)
  • 2020-12-13 15:17

    The fill_between() command creates a PolyCollection that is not supported by the legend() command.

    Therefore you will have to use another matplotlib artist (compatible with legend()) as a proxy, without adding it to the axes (so the proxy artist will not be drawn in the main axes) and feed it to the legend function. (see the matplotlib legend guide for more details)

    In your case, the code below should fix your problem:

    from matplotlib.patches import Rectangle
    
    p1 = Rectangle((0, 0), 1, 1, fc="green")
    p2 = Rectangle((0, 0), 1, 1, fc="red")
    legend([p1, p2], [a1_label, a2_label])
    

    image

    0 讨论(0)
提交回复
热议问题