【问题标题】:setting margins in matplotlib/seaborn with subplots在 matplotlib/seaborn 中使用子图设置边距
【发布时间】:2015-12-17 01:00:04
【问题描述】:

我正在使用 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 参数似乎没有效果。这是怎么做到的?

【问题讨论】:

  • 我认为stackoverflow.com/questions/6230627/… 的答案比您链接的那个更好。对你起作用吗? (P.S. - 一个 complete 小型可运行示例会更令人愉快。)
  • @cphlewis:你说得对,我添加了一个完整的小例子

标签: python matplotlib seaborn


【解决方案1】:

您可以定义一个函数以将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)

这是产生的数字:

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

【讨论】:

  • 我用sns.tsplot添加了一个完整的例子,但是这不起作用。
  • 这个功能对我来说仍然可以正常工作。我将更新我的示例以在您的最小示例中显示它。
猜你喜欢
  • 2019-07-11
  • 1970-01-01
  • 2021-10-17
  • 2018-02-15
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 1970-01-01
相关资源
最近更新 更多