Plot is shifted by 1 unit when overlaying two with same axes (Seaborn/Matplotlib)

Viewed 558

I am trying to plot a regression line over a boxplot using Seaborn.

It seems like the regression plot is being shifted by 1 x-axis unit. This causes the regression to start at x=2 instead of x=1, but with the value of x=1. This also causes the regression plot to extend outside the limits of the boxplot (x=7). I have recreated the issue using the "tips" dataset to make a minimal reproduceable example and have included an image of the figure.

How do I resolve this issue so that both plots start and end at the same values?

Update: I ran this code on another machine and it produced the correct plot. So I'm curious about what may be causing the issue on the specific desktop I used originally. (Windows 10, Anacaonda Environment, Python 3.6.10). I'm not running this in a Jupyter notebook

Thanks!

tips = sns.load_dataset("tips")

fig, ax = plt.subplots()
sns.boxplot(x="size", y="tip", data=tips, ax=ax)
sns.regplot(x="size", y="tip", data=tips, ax=ax, scatter=False, order=2)

plt.show()

Regplot overlayed onto Boxplot

1 Answers

Issue

I think issue here is, that seaborn uses matplotlibs boxplot with positions/xticks starting with 0. Thus, in your example [0,1,...,5]. The xtickslabels are actually offset by 1:

print(ax.get_xticklabels())
[Text(0, 0, '1'), Text(1, 0, '2'), Text(2, 0, '3'), Text(3, 0, '4'), Text(4, 0, '5'), Text(5, 0, '6')]

Workaround

matplotlib allows to set the positions during boxplot construction. However, passing the along with seaborns boxplot will cause an error because the positions argument is actually provided two times.

sns.boxplot(x="size", y="tip", data=tips, ax=ax, positions=[1,2,3,4,5,6])
TypeError: matplotlib.axes._axes.Axes.boxplot() got multiple values for keyword argument 'positions'

Thus, the only solutions I can imagine is to either to use matplotlib directly without seaborn or to adjust the data to fit the xticks, e.g. by inserting tips['size'] -= 1 before the second plot in your example.

Related