Seaborn箱线图横线注释

4
我想在一些图表中添加水平线,即“目标”线:条纹图、箱线图和小提琴图,以显示理想值数据(或理想范围)。这个R示例(Add multiple horizontal lines in a boxplot)-第一张图片-基本上就是它(尽管我会进行一些格式化使其更具可读性)。 R abline() equivalent in Python对我没有帮助(或者我还没有弄清楚如何使用),因为我正在使用分类数据,所以我只想基本定义(例如)y=3并绘制它。我的代码(如下)运行良好,我只是不知道如何添加一条线。
fig, ax = plt.subplots(nrows=4,figsize=(20,20))

sns.violinplot(x="Wafer", y="Means", hue='Feature', 
           data=Means[Means.Target == 1], ax=ax[0])
sns.violinplot(x="Wafer", y="Means", hue='Feature', 
           data=Means[Means.Target == 3], ax=ax[1])
sns.boxplot(x="Feature", y="Means", 
        data=Means, linewidth=0.8, ax=ax[2])
sns.stripplot(x="Feature", y="Means", hue='Wafer',
          data=Means, palette="plasma", jitter=0.1, size=5.5, ax=ax[3])

任何帮助都非常感激。

1
应该是plt.hlines(y, xmin, xmax) - Sheldore
2个回答

6
假设您想在高度为y的位置绘制一条水平线,并且从x1x2,其中x1x2是实际的x数据值。以下是可能有几种方法中的三种:
第一种方法:
ax.hlines(y, x1, x2)

第二点:

plt.plot([x1, x2], [y, y])

第三步(x1x2现在以相对/分数坐标表示,介于0表示极左和1表示极右之间):

ax.axhline(y, x1, x2)

谢谢 - 你的第三个版本正是我想要的。如何对多行进行操作:例如 ax.axhline[(3, 0, 1),(1,0,1)](无法工作),如果我想要在 y=3y=1 处画一条线? - BAC83
好的,那么您只需要写两行代码:ax.axhline(1, 0, 1)ax.axhline(3, 0, 1)。您也可以将其放在一个 for 循环中,但是对于仅有两行的情况,我认为这并不必要。 - Sheldore
我实际上是用for循环来完成的,因为在我的代码上下文中,我无法通过调用函数两次来使其工作。感谢for循环的帮助。 - BAC83

2

如果你想定义一个好或坏的区域,我通常会在数据后面放置一个补丁,以便用户更容易理解。

fig, ax = plt.subplots(figsize=(4, 4))
ax.plot([1,2,3,4], [1,2,3,4], color='blue')  # simple example line

# define patch area
rect = patches.Rectangle(
    xy=(ax.get_xlim()[0], 2),  # lower left corner of box: beginning of x-axis range & y coord)
    width=ax.get_xlim()[1]-ax.get_xlim()[0],  # width from x-axis range
    height=1,
    color='green', alpha=0.1, ec='red'
)
ax.add_patch(rect)
plt.show()

enter image description here


谢谢ak_slick,这是一个非常好的观点;我会尝试实施并反馈。 - BAC83

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接