I'm plotting data using seaborn's swarm
method. After the plot is drawn, I'd like to retrieve the (x,y)
-coordinates of the drawn points.
My application for this is: I want to add a legend to the plot, and automatically (I have a large number of plots…) decide whether to display the legend inside or outside the plot. For this, I'd first draw the legend inside, get its bounding box, and check whether any of the drawn points overlap that bounding box. If that is the case, redraw the whole plot with the legend outside.
Is it possible to retrieve the coordinates of the drawn points? I tried iterating over the axes's get_children()
, but there seem to be other artists in there, which are not points and which cause my legend to go outside even if it would not overlap with any data points.
Looking at the code, I don't see any obvious way of doing this, since the coordinates from the beeswarm()
method don't seem to be stored anywhere, but perhaps I missed something?
Thanks in any case,
Lukas
Edit: Here's a minimal example:
test_data = pd.DataFrame([
{'x': 1, 'y': 1.0, 'color': 1.0},
{'x': 1, 'y': 2.0, 'color': 0.5},
{'x': 1, 'y': 2.8, 'color': 0.25},
{'x': 1, 'y': 4.0, 'color': 0.125},
{'x': 2, 'y': 1.0, 'color': 1.0},
{'x': 2, 'y': 2.0, 'color': 0.5},
{'x': 2, 'y': 2.7, 'color': 0.25},
{'x': 2, 'y': 4.0, 'color': 0.125},
{'x': 3, 'y': 1.0, 'color': 1.0},
{'x': 3, 'y': 2.0, 'color': 0.5},
{'x': 3, 'y': 2.7, 'color': 0.25},
{'x': 3, 'y': 4.0, 'color': 0.125},
])
p = sns.swarmplot(data=test_data, x='x', y='y', hue='color')
legend = p.legend(frameon=True)
legend.get_frame().set_fc('gray')
I'd like to detect that the legend overlaps the top-rightmost point and draw it outside the plot.