【问题标题】:Specify axis-data margin in matplotlib在 matplotlib 中指定轴数据边距
【发布时间】:2020-01-14 16:49:01
【问题描述】:

我在 y 轴上有一系列带有分类数据的图。似乎轴和数据之间的额外边距与 y 轴上的类别数相关。如果类别很多,则会出现额外的边距,但如果类别很少,则边距太小,以至于数据点被切割。情节如下所示:

类别少,边距太小的情节:

类别多且边距过大的情节(点击查看完整尺寸):

目前,我只找到了处理绘图周围空白的解决方案,例如bbox_inches='tight' 或fig.tight_layout(),但这并不能解决我的问题。 我的x轴没有这样的问题,请问这是x轴只包含数值和y轴分类数据的问题吗?

我用来生成所有图的代码如下所示:

sns.set(style='whitegrid')
plt.xlim(left=left_lim, right=right_lim)
plt.xticks(np.arange(left_lim, right_lim, step))
plot = sns.scatterplot(method.loc[:,'Len'], 
                       method.loc[:,'Bond'],
                       hue = method.loc[:,'temp'],
                       palette= palette,
                       legend = False, 
                       s = 50)

set_size(width, height)
plt.savefig("method.png", dpi = 100, bbox_inches='tight', pad_inches=0)
plt.show()

set_size() 来自Axes class - set explicitly size (width/height) of axes in given units 的第一个答案。

【问题讨论】:

  • 每边的边距始终为 5%。这意味着绝对单位的空间越大,数字越大。因此,如何使用相同边距的解决方案将取决于您如何确定图形大小。 (本题不包含代码!)

标签: python matplotlib


【解决方案1】:

我们可以稍微修改Axes class - set explicitly size (width/height) of axes in given units的功能 添加一条线来设置轴边距。

import matplotlib.pyplot as plt

def set_size(w,h, ax=None, marg=(0.1, 0.1)):
    """ w, h: width, height in inches """
    if not ax: ax=plt.gca()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom
    figw = float(w)/(r-l)
    figh = float(h)/(t-b)
    ax.figure.set_size_inches(figw, figh)
    ax.margins(x=marg[0]/w, y=marg[1]/h)

并用

调用它
set_size(width, height, marg=(xmargin, ymargin))

其中xmargin, ymargin 是以英寸为单位的边距。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 2012-06-18
    • 2015-11-02
    • 2018-09-27
    • 1970-01-01
    • 2012-09-10
    相关资源
    最近更新 更多