Skip to content
Advertisement

seaborn pointplot and boxplot in one plot but shifted on the x-axis

I want to plot both a boxplot and the mean in one figure. So far my plot looks like this using these lines of code:

JavaScript

enter image description here

I would like to shift my mean ‘x’ markers a bit to the right so that the errorbars don’t overlap with the whiskers from the boxplot. Any idea how to do that? A bonus question: how do I insert a legend in this plot saying “x: mean, o: data values” elegantly?


Build my dataframe

JavaScript

Advertisement

Answer

In order to shift points on a plot, one may use a transform; in this case a ScaledTranslation is useful. Unfortunately, seaborn does not allow to use the transform directly and does not give access to the plotted objects. Therefore one needs to get the plotted object (in this case the PathCollection) from the axes. If the plot to be offset is the first plot in the axes ax, we might simply get it via ax.collections[0]. Then we can set the transform to it via .set_transform.

JavaScript

Complete code:

JavaScript

enter image description here

To shift the lineplot as well, you would need to do the same as above with its scatter points (ax.collections[1]) and for all the lines in the plot (ax.lines)

JavaScript
Advertisement