首页 文章

为什么我的matlab插图在我的matplotlib图中切断了?

提问于
浏览
189

我正在使用 matplotlib 绘制数据集,其中我有一个相当"tall"的xlabel(它是在TeX中呈现的包含分数的公式,因此其高度相当于几行文本) .

在任何情况下,当我绘制数字时,公式的底部总是被切断 . 改变图形大小似乎没有帮助,我无法弄清楚如何将x轴“向上”移动以为xlabel腾出空间 . 这样的事情将是一个合理的临时解决方案,但更好的方法是让matplotlib自动识别标签被切断并相应调整大小 .

这是我的意思的一个例子:

import matplotlib.pyplot as plt

plt.figure()
plt.ylabel(r'$\ln\left(\frac{x_a-x_b}{x_a-x_c}\right)$')
plt.xlabel(r'$\ln\left(\frac{x_a-x_d}{x_a-x_e}\right)$')
plt.show()

当你可以看到整个ylabel时,xlabel在底部被切断 .

在这是特定于机器的问题的情况下,我在OSX 10.6.8上使用matplotlib 1.0.0运行它

5 回答

  • 5

    使用:

    import matplotlib.pyplot as plt
    
    plt.gcf().subplots_adjust(bottom=0.15)
    

    为标签腾出空间 .

    编辑:

    由于我给出了答案, matplotlib 添加了 tight_layout() 函数 . 所以我建议使用它:

    plt.tight_layout()
    

    应该为xlabel腾出空间 .

  • 1

    一个简单的选择是配置matplotlib以自动调整绘图大小 . 它对我来说非常合适,我不确定为什么默认情况下它没有被激活 .

    Method 1

    在matplotlibrc文件中设置它

    figure.autolayout : True
    

    有关自定义matplotlibrc文件的更多信息,请参见此处:http://matplotlib.org/users/customizing.html

    Method 2

    像运行时一样在运行时更新rcParams

    from matplotlib import rcParams
    rcParams.update({'figure.autolayout': True})
    

    使用此方法的优点是您的代码将在不同配置的计算机上生成相同的图形 .

  • 278

    如果要将其存储到文件中,可以使用 bbox_inches="tight" 参数解决它:

    plt.savefig('myfile.png', bbox_inches = "tight")
    
  • 6

    您还可以在 $HOME/.matplotlib/matplotlib_rc 中将自定义填充设置为默认值,如下所示 . 在下面的示例中,我修改了底部和左侧开箱即用的填充:

    # The figure subplot parameters.  All dimensions are a fraction of the
    # figure width or height
    figure.subplot.left  : 0.1 #left side of the subplots of the figure
    #figure.subplot.right : 0.9 
    figure.subplot.bottom : 0.15
    ...
    
  • 107

    在图表上的所有更改之后放置 plot.tight_layout() ,就在 show()savefig() 之前将解决问题 .

相关问题