Move and resize legends-box in matplotlib

后端 未结 2 711
鱼传尺愫
鱼传尺愫 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: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

提交回复
热议问题