在 swarmplot 上绘制另一个点

Plot another point on top of swarmplot

我想像这样在 swarmplot 顶部绘制一个 "highlighted" 点

swarmplot 没有 y 轴,所以我不知道如何绘制那个点。

import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.swarmplot(x=tips["total_bill"])

此方法基于了解您希望突出显示的数据点的索引,但它应该有效 - 尽管如果您在单个 Axes 实例上有多个群图,它会变得稍微复杂一些。

import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.swarmplot(x=tips["total_bill"])
artists = ax.get_children()
offsets = []
for a in artists:
    if type(a) is matplotlib.collections.PathCollection:
        offsets = a.get_offsets()
        break
plt.scatter(offsets[50,0], offsets[50,1], marker='o', color='orange', zorder=10)

如果您为 y 轴添加分组变量(以便它们显示为一个组),则可以使用 hue 属性突出显示 point/s,然后使用另一个变量突出显示您有兴趣。

然后您可以删除 y 标签以及样式和图例。

import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="whitegrid")

# Get data and mark point you want to highlight
tips = sns.load_dataset("tips")
tips['highlighted_point'] = 0
tips.loc[tips[tips.total_bill > 50].index, 'highlighted_point'] = 1

# Add holding 'group' variable so they appear as one
tips['y_variable'] = 'testing'

# Use 'hue' to differentiate the highlighted point
ax = sns.swarmplot(x=tips["total_bill"], y=tips['y_variable'], hue=tips['highlighted_point'])

# Remove legend
ax.get_legend().remove()

# Hide y axis formatting 
ax.set_ylabel('')
ax.get_yaxis().set_ticks([])
plt.show()