如何在Seaborn的边缘单变量图中用黑色虚线和数字注释

时间:2019-08-31 13:43:43

标签: python matplotlib seaborn

这是我的代码:

import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats

tips = sns.load_dataset("tips")

sns.set(style="ticks", color_codes=True)

g = sns.JointGrid(x="total_bill", y="tip", data=tips)

g.plot_joint(sns.regplot, line_kws={"color": "coral"}, scatter_kws={"color": "gray"})
plt.grid()
rsquare = lambda a, b: stats.pearsonr(a, b)[0] ** 2
g = g.annotate(rsquare, template="{stat}: {val:.2f}", stat="$R^2$", loc="upper left", fontsize=12)

g = g.plot_marginals(sns.kdeplot, color="steelblue", shade=True, linewidth=3)

marg_x = g.ax_marg_x
marg_y = g.ax_marg_y
marg_x.annotate('15', xy=(15, 0), xytext=(15, 1), arrowprops=dict(facecolor='k', arrowstyle='-' ))
marg_x.annotate('25', xy=(25, 0), xytext=(25, 1), arrowprops=dict(facecolor='k', arrowstyle='-' ))
marg_y.annotate('2', xy=(0, 2),xytext=(1, 2), arrowprops=dict(facecolor='k', arrowstyle='-' ))
marg_y.annotate('4', xy=(0, 4),xytext=(1, 4), arrowprops=dict(facecolor='k', arrowstyle='-' ))

plt.show()

从代码中可以看到,我想用黑线注释marg_x和marg_y,但似乎marg_x和marg_y用白线注释了,数字('15','25', '2','4')完全不显示。另外,我更喜欢虚线。我应该如何注释?

PS:运行代码时,我得到如下警告:

  

D:\ pycharm \ PyCharm 2018.3 \ helpers \ pycharm_matplotlib_backend \ backend_interagg.py:62:UserWarning:不应用紧凑的布局。底边距和顶边距不能足够大以容纳所有轴装饰。     self.figure.tight_layout()   此警告是否与我的问题有关?

1 个答案:

答案 0 :(得分:0)

我发现有一个简单的方法,就是使用Axes.plot。实际上,这是我想到的第一个答案,但是当时我设置了错误的参数,所以我切换到Axes.annotate。以下是最终代码。

import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats

tips = sns.load_dataset("tips")

sns.set(style="ticks", color_codes=True)

g = sns.JointGrid(x="total_bill", y="tip", data=tips)

g.plot_joint(sns.regplot, line_kws={"color": "coral"}, scatter_kws={"color": "gray"})
plt.grid()
rsquare = lambda a, b: stats.pearsonr(a, b)[0] ** 2
g = g.annotate(rsquare, template="{stat}: {val:.2f}", stat="$R^2$", loc="upper left", fontsize=12)

g = g.plot_marginals(sns.kdeplot, color="steelblue", shade=True, linewidth=3)

marg_x = g.ax_marg_x
marg_y = g.ax_marg_y
x = [2,2]
y = [0,0.05]
marg_x.plot(x,y,'k--')

x = [4,4]
y = [0,0.05]
marg_x.plot(x,y,'k--')


y = [4,4]
x = [0,0.4]
marg_y.plot(x,y,'k--')

y = [7,7]
x = [0,0.4]
marg_y.plot(x,y,'k--')

plt.show()