Matplotlib adjust figure margin

后端 未结 7 768
盖世英雄少女心
盖世英雄少女心 2021-01-31 15:48

The following code gives me a plot with significant margins above and below the figure. I don\'t know how to eliminate the noticeable margins. subplots_adjust does

相关标签:
7条回答
  • 2021-01-31 16:19

    I just discovered how to eliminate all margins from my figures. I didn't use tight_layout(), instead I used:

    import matplotlib.pyplot as plt
    fig = plt.figure(figsize=(20,20))
    ax = plt.subplot(111,aspect = 'equal')
    plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-31 16:21

    I think what you need is, and it works well for me.

    plt.axis('tight')
    

    This command will automatically scale the axis to fit tightly to the data. Also check the answer of Nuno Aniceto for a customized axis. The documents are in https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.axis.

    Be aware that

    plt.savefig(filename, bbox_inches='tight')
    

    will help remove white space of all the figure including labels, etc, but not the white space inside the axes.

    0 讨论(0)
  • 2021-01-31 16:22

    You can use like: plt.subplots_adjust(wspace=1, hspace=0.5,left=0.1,top=0.9,right=0.9,bottom=0.1) And delete the item:bbox_inches='tight' in plt.savefig().

    0 讨论(0)
  • 2021-01-31 16:24

    tight_layout(pad=0) will meet your need. http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout

    0 讨论(0)
  • 2021-01-31 16:26

    You should use add_axes if you want exact control of the figure layout. eg.

    left = 0.05
    bottom = 0.05 
    width = 0.9
    height = 0.9
    ax = fig.add_axes([left, bottom, width, height])
    
    0 讨论(0)
  • 2021-01-31 16:33

    I think the subplot_adjust call is irrelevant here since the adjustment is overridden by tight_layout. Anyway, this only change the size of the axes inside the figure.

    As tcaswell pointed it, you need to change the size of the figure. Either at creation (my proposition below) or after, using fig.set_size_inches. I'm here creating a figure with a 1:1 aspect ratio using the figsize=(6,6) argument (of course 6 inches is an arbitrary choice):

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure(figsize=(6,6))
    ax = fig.add_subplot(111)
    ax.plot(range(10),range(10))
    ax.set_aspect('equal')
    plt.tight_layout()
    
    0 讨论(0)
提交回复
热议问题