Exact figure size in matplotlib with title, axis labels

前端 未结 2 1138
滥情空心
滥情空心 2020-12-25 14:12

Similar questions have been asked before, but all of my search results don\'t address my problem. Take the following example code:

from matplotlib.pyplot i         


        
相关标签:
2条回答
  • 2020-12-25 14:31

    In agreement with the comment from David Robinson, the figure produced here is 3.25 by 3 inches as measured by photoshop, although the xlabel does show cut-off (mpl 1.1.0 in python 2.6 64-bit, win7)

    A solution to overcome the problem is to manually adjust the margins with subplot_adjust:

    from matplotlib.pyplot import *
    fig = figure(1, figsize=(3.25, 3))
    plot([0, 1, 5, 2, 9])
    title('title')
    xlabel('xAxis')
    ylabel('yAxis')
    subplots_adjust(bottom=0.14)   # <--
    fig.savefig('test.png', dpi=600) 
    

    The default value of these margins are set in the matploblibrc file and you can modify it there permanently. The default value for the bottom margin in my case was 0.10.

    Either if your figure is of a wrong size or correct, as in my case, you can use subplot_adjust to provide enough space for the label. Then if needed, you can calculate the correction to get the actual picture or figure size you want as you already did.

    The final view of the saved figure depends on the size of that figure. If you show() your figure and you save it from the matplotlib view frame you get the label cut-off in the image. But if you increase manually the size of the image you will see the label appearing and if you save it then it will also appear in the saved image. Lets say that is WYSIWYG. Your figure is of a very small size and this makes your label to get cut. So another approach is to make a bigger figure maybe with lower dpi to keep overall size. This also works:

    from matplotlib.pyplot import *
    fig = figure(1, figsize=(6.5, 6))   # <---
    plot([0, 1, 5, 2, 9])
    title('title')
    xlabel('xAxis')
    ylabel('yAxis')
    fig.savefig('test.png', dpi=300)    # <---
    

    In any case, I would consider this as a matplolib bug, as you could expect to have an uncut figure after plot and save.

    0 讨论(0)
  • 2020-12-25 14:35

    matplotlib 1.1.1 has added figure.tight_layout() (doc) that will do this for you.

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