我使用以下方法绘制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-margin更大,但x
的{{1}}参数似乎没有效果。怎么办呢?
答案 0 :(得分:3)
您可以定义一个函数,将x
和y
范围的给定部分添加到边距,这样可以使用get_xlim
,get_ylim
,{{1 }和set_xlim
。使用最小的例子:
set_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()
这是产生的数字:
与原始数字相比,显然增加了利润率: