Get legend as a separate picture in Matplotlib

后端 未结 9 925
情歌与酒
情歌与酒 2020-11-29 03:50

I\'m developing a Web application and want to display a figure and its legend in different locations on the page. Which means I need to save the legend as a separate png fil

9条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 04:19

    In November 2020, I tried almost everything on this post, but none worked for me. After struggling for a while, I found a solution that does what I want.

    Pretend you want to draw a figure and a legend separately that looks like below (apparently I don't have enough reputation to embed pictures in a post; click the links to see the picture).

    import matplotlib.pyplot as plt
    %matplotlib inline
    
    fig, ax = plt.subplots()
    
    ax.plot([1, 2, 3], label="test1")
    ax.plot([3, 2, 1], label="test2")
    
    ax.legend()
    

    target figure

    You can separate the figure and the legend in two different ax objects:

    fig, [ax1, ax2] = plt.subplots(1, 2)
    
    ax1.plot([1, 2, 3], label="test1")
    ax1.plot([3, 2, 1], label="test2")
    
    ax2.plot([1, 2, 3], label="test1")
    ax2.plot([3, 2, 1], label="test2")
    h, l = ax2.get_legend_handles_labels()
    ax2.clear()
    ax2.legend(h, l, loc='upper left')
    ax2.axis('off')
    

    fixed figure 1

    You can easily control where the legend should go:

    fig, [ax1, ax2] = plt.subplots(2, 1)
    
    ax1.plot([1, 2, 3], label="test1")
    ax1.plot([3, 2, 1], label="test2")
    
    ax2.plot([1, 2, 3], label="test1")
    ax2.plot([3, 2, 1], label="test2")
    h, l = ax2.get_legend_handles_labels()
    ax2.clear()
    ax2.legend(h, l, loc='upper left')
    ax2.axis('off')
    

    fixed figure 2

提交回复
热议问题