My matplotlib.pyplot legend is being cut off

后端 未结 5 671
时光取名叫无心
时光取名叫无心 2021-02-01 01:33

I\'m attempting to create a plot with a legend to the side of it using matplotlib. I can see that the plot is being created, but the image bounds do not allow the entire legend

5条回答
  •  一向
    一向 (楼主)
    2021-02-01 02:13

    As pointed by Adam, you need to make space on the side of your graph. If you want to fine tune the needed space, you may want to look at the add_axes method of matplotlib.pyplot.artist.

    Below is a rapid example:

    import matplotlib.pyplot as plt
    import numpy as np
    
    # some data
    x = np.arange(0, 10, 0.1)
    y1 = np.sin(x)
    y2 = np.cos(x)
    
    # plot of the data
    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.6, 0.75])
    ax.plot(x, y1,'-k', lw=2, label='black sin(x)')
    ax.plot(x, y2,'-r', lw=2, label='red cos(x)')
    ax.set_xlabel('x', size=22)
    ax.set_ylabel('y', size=22)
    ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    
    plt.show()
    

    and the resulting image: image

提交回复
热议问题