Move and resize legends-box in matplotlib

后端 未结 2 696
鱼传尺愫
鱼传尺愫 2021-01-04 04:44

I\'m creating plots using Matplotlib that I save as SVG, export to .pdf + .pdf_tex using Inkscape, and include the .pdf_tex-file in a LaTeX document.

This means tha

相关标签:
2条回答
  • 2021-01-04 05:27

    You may use the bbox_to_anchor and bbox_transform parameters to help you setting the anchor for your legend:

    ax = plt.gca()
    plt.legend(bbox_to_anchor=(1.1, 1.1), bbox_transform=ax.transAxes)
    

    Note that (1.1, 1.1) are in the axes coordinates in this example. If you wish to use the data coordinates you have to use bbox_transform=ax.transData instead.

    0 讨论(0)
  • 2021-01-04 05:39

    You can move a legend after automatically placing it by drawing it, and then getting the bbox position. Here's an example:

    import matplotlib.pyplot as plt
    import numpy as np
    
    # Plot data
    x = np.linspace(0,1,100)
    y = x**2
    fig = plt.figure()
    ax = fig.add_subplot(221) #small subplot to show how the legend has moved. 
    
    # Create legend
    plt.plot(x, y, label = '{\\footnotesize \$y = x^2\$}')
    leg = plt.legend( loc = 'upper right')
    
    plt.draw() # Draw the figure so you can find the positon of the legend. 
    
    # Get the bounding box of the original legend
    bb = leg.get_bbox_to_anchor().inverse_transformed(ax.transAxes)
    
    # Change to location of the legend. 
    xOffset = 1.5
    bb.x0 += xOffset
    bb.x1 += xOffset
    leg.set_bbox_to_anchor(bb, transform = ax.transAxes)
    
    
    # Update the plot
    plt.show()
    

    legend moved after first drawing

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