使用子图在 matplotlib/seaborn 中设置边距

setting margins in matplotlib/seaborn with subplots

我正在 matplotlib/seaborn 中使用以下方法绘制子图:

plt.figure()
s1 = plt.subplot(2, 1, 1)
# plot 1 
# call seaborn here
s2 = plt.subplot(2, 1, 2)
# plot 2
plt.tight_layout()
plt.show()

我正在 运行 解决标记被轴隐藏的常见问题 (Add margin when plots run against the edge of the graph)。当我尝试调整边距时它不起作用:

s1 = plt.subplot(2, 1, 1)
s1.margins(0.05)

它没有给出错误,但也没有设置边距。

这里有一个完整的例子:

gammas = sns.load_dataset("gammas")
s = plt.subplot(1, 1, 1)
# this does not change the x margins
s.get_axes().margins(x=0.05, y=0.01)
ax = sns.tsplot(time="timepoint", value="BOLD signal",
                unit="subject", condition="ROI",
                err_style="ci_bars",
                interpolate=False,
                data=gammas)
plt.show()

在上面,我试图使 x 边距更大,但是 margins()x 参数似乎没有效果。如何做到这一点?

您可以定义一个函数,将 xy 范围的给定部分添加到边距,这利用了 get_xlimget_ylimset_xlimset_ylim。使用您的最小示例:

import matplotlib.pyplot as plt
import seaborn as sns

def add_margin(ax,x=0.05,y=0.05):
    # This will, by default, add 5% to the x and y margins. You 
    # can customise this using the x and y arguments when you call it.

    xlim = ax.get_xlim()
    ylim = ax.get_ylim()

    xmargin = (xlim[1]-xlim[0])*x
    ymargin = (ylim[1]-ylim[0])*y

    ax.set_xlim(xlim[0]-xmargin,xlim[1]+xmargin)
    ax.set_ylim(ylim[0]-ymargin,ylim[1]+ymargin)

gammas = sns.load_dataset("gammas")
s = plt.subplot(1, 1, 1)
ax = sns.tsplot(time="timepoint", value="BOLD signal",
                unit="subject", condition="ROI",
                err_style="ci_bars",
                interpolate=False,
                data=gammas)

# Check what the original limits were
x0,y0=s.get_xlim(),s.get_ylim()

# Update the limits using set_xlim and set_ylim
add_margin(s,x=0.05,y=0.01) ### Call this after tsplot 

# Check the new limits
x1,y1=s.get_xlim(),s.get_ylim()

# Print the old and new limits
print x0,y0
print x1,y1

plt.show()

打印:

# The original limits
(-0.10101010101010099, 10.1010101010101) (-2.0, 3.0)
# The updated limits
(-0.61111111111111105, 10.611111111111111) (-2.0499999999999998, 3.0499999999999998)

这是生成的数字:

与原图相比,明显增加了边距: