Plot another point on top of swarmplot

1.1k Views Asked by At

I want to plot a "highlighted" point on top of swarmplot like this

enter image description here

The swarmplot don't have the y-axis, so I have no idea how to plot that point.

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

There are 2 best solutions below

5
On BEST ANSWER

This approach is predicated on knowing the index of the data point you wish to highlight, but it should work - although if you have multiple swarmplots on a single Axes instance it will become slightly more complex.

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)

enter image description here

0
On

You can highlight a point/s using the hue attribute if you add a grouping variable for the y axis (so that they appear as a single group), and then use another variable to highlight the point that you're interested in.

Then you can remove the y labels and styling and legend.

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()

Output plot