在 matplotlib/seaborn 中设置子图的边距

lgd*_*lgd 1 python matplotlib seaborn

我正在使用以下命令在 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()
Run Code Online (Sandbox Code Playgroud)

我遇到了标记被轴隐藏的常见问题(当绘图靠近图形边缘时添加边距)。当我尝试调整边距时,它不起作用:

s1 = plt.subplot(2, 1, 1)
s1.margins(0.05)
Run Code Online (Sandbox Code Playgroud)

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

这是一个完整的例子:

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()
Run Code Online (Sandbox Code Playgroud)

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

tmd*_*son 5

x您可以定义一个函数,将和范围的给定分数添加到边距,该函数y使用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()
Run Code Online (Sandbox Code Playgroud)

哪个打印:

# The original limits
(-0.10101010101010099, 10.1010101010101) (-2.0, 3.0)
# The updated limits
(-0.61111111111111105, 10.611111111111111) (-2.0499999999999998, 3.0499999999999998)
Run Code Online (Sandbox Code Playgroud)

这是生成的数字:

在此输入图像描述

与原始数字相比,显然增加了边距:

在此输入图像描述