【问题标题】:Plot another point on top of swarmplot在 swarmplot 上绘制另一个点
【发布时间】:2020-07-13 02:16:13
【问题描述】:

我想像这样在 swarmplot 上绘制一个“突出显示”的点

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

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

【问题讨论】:

  • 可能只使用特定的 x 值(在这种情况下为tips["total_bill"])和零作为 y 值就足够了。散点按从左到右的顺序排列。或者您可以在调用swarmplot 之前通过此列对完整的数据框进行排序。
  • 尝试对数据进行排序。我有很多子图,每个子图都需要排序,所以有点棘手

标签: python matplotlib data-visualization seaborn swarmplot


【解决方案1】:

这种方法基于知道您希望突出显示的数据点的索引,但它应该可以工作 - 尽管如果您在单个 Axes 实例上有多个 swarmplot,它会变得稍微复杂一些。

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)

【讨论】:

  • 还有一个问题。你怎么知道那个点的数据?我想知道原始数据中的“50”点在哪里。
  • offsets = a.get_offsets() 存储绘制点的位置 - 至关重要的是,它们以与绘制相同的顺序存储。因此 offsets[50] 的数据应该与 @ 的数据相同987654327@。没有其他方法可以从 swarmplot 中提取数据
  • 我认为 get_offsets() 中的索引是排序列表的索引?原始数据未排序
  • @ChrisMaverick 你可能是对的,我可能把它和matplotlib.Line2D.get_data() 混淆了,虽然文档没有说明
  • 所以...我应该对原始数据进行排序还是什么?
【解决方案2】:

如果您为 y 轴添加一个分组变量(以便它们显示为一个组),您可以使用 hue 属性突出显示一个点,然后使用另一个变量突出显示您感兴趣的点.

然后您可以删除 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2020-05-30
    • 2010-09-25
    相关资源
    最近更新 更多