Python:seaborn pointplot和boxplot在一个绘图中,但在xaxis上移动

2024-10-01 17:38:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个数字中同时绘制箱线图和平均值。到目前为止,使用以下代码行,我的图是这样的:

sns.swarmplot(x="stimulus", y="data", data=spi_num.astype(np.float), edgecolor="black", linewidth=.9)
sns.boxplot(x="stimulus", y="data", data=spi_num.astype(np.float), saturation=1)
sns.pointplot(x="stimulus", y="data", data=spi_num.astype(np.float), linestyles='', scale=1, color='k', errwidth=1.5, capsize=0.2, markers='x')
sns.pointplot(x="stimulus", y="data", data=spi_num.astype(np.float), linestyles='--', scale=0.4, color='k', errwidth=0, capsize=0)
plt.ylabel("number of spikes")
plt.title("Median Number of Spikes");

enter image description here

我想把我的平均'x'标记向右移动一点,这样错误条就不会与方框图中的胡须重叠。你知道怎么做吗?一个额外的问题:我如何在这个图中插入一个图例,优雅地说“x:平均值,o:数据值”?在


构建我的数据帧

^{pr2}$

Tags: spidatanpfloatnumcolor平均值scale
1条回答
网友
1楼 · 发布于 2024-10-01 17:38:37

为了移动图上的点,可以使用转换;在这种情况下,ScaledTranslation是有用的。不幸的是,seaborn不允许直接使用转换,也不允许访问绘制的对象。因此,需要从轴获取打印对象(在本例中为PathCollection)。如果要偏移的绘图是ax轴上的第一个绘图,我们可以通过ax.collections[0]得到它。然后我们可以通过.set_transform设置对它的转换。在

fig, ax = plt.subplots()
sns.pointplot(... , ax=ax)
#produce transform with 5 points offset in x direction
offset = transforms.ScaledTranslation(5/72., 0, ax.figure.dpi_scale_trans)
trans = ax.collections[0].get_transform()
ax.collections[0].set_transform(trans + offset)

完整代码:

^{pr2}$

enter image description here

要同时移动线条图,您需要对其散点(ax.collections[1])和绘图中的所有线条(ax.lines)执行与上面相同的操作

sns.pointplot(x="stimulus", y="data", data=spi_num, linestyles=' ', scale=0.4, 
              color='k', errwidth=0, capsize=0, ax=ax, gid="Nm")
# shift points of connecting line:
trans = ax.collections[1].get_transform()
ax.collections[1].set_transform(trans + offset)
# shift everything else:
for line in ax.lines:
    trans = line.get_transform()
    line.set_transform(trans + offset)

相关问题 更多 >

    热门问题