Creating figure with exact size and no padding (and legend outside the axes)

前端 未结 2 1957
孤城傲影
孤城傲影 2020-11-27 17:59

I am trying to make some figures for a scientific article, so I want my figures to have a specific size. I also see that Matplotlib by default adds a lot of padding on the b

2条回答
  •  孤城傲影
    2020-11-27 18:54

    As of matplotlib==3.1.3, you can use constrained_layout=True to achieve the desired result. This is currently experimental, but see the docs for a very helpful guide (and the section specifically on legends). Note that the legend will steal space from the plot, but this is unavoidable. I've found that as long as the legend does not take up too much space relative to the size of the plot, then the figure gets saved without cropping anything.

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(figsize=(3, 2), constrained_layout=True)
    ax.set_title('title')
    ax.set_ylabel('y label')
    ax.set_xlabel('x label')
    ax.plot([0,1], [0,1], label='my text here')
    ax.legend(loc='center left', bbox_to_anchor=(1.1, 0.5))
    fig.savefig('figure03.pdf')
    

    The saved figure.

提交回复
热议问题