Skip to content
Advertisement

How to align the x position of the dots in seaborn scatterplot to a nested bar plot

I am trying to plot a scatter plot on top of a bar plot using sns.scatterplot() and df.plot(kind='bar'); The figure turns out to be fine, but it would be even nicer if I can align each of the scatter points to its corresponding bar with an identical label.

The current plot

I have read the document on Rectangle of matplotlib.pyplot that it has a get_x() method that can “Return the left coordinate of the rectangle”;

I wonder if there is a way for me to assign these coordinates to the scatter points that’d be plotted by seaborn?

Code

JavaScript

Dataframes

bar_df

year apple banana citrus
2020 12 34 56 78
2025 12 34 56 78
2030 12 34 56 78
2035 12 34 56 78

line_df

year apple banana citrus
2020 23 45 67 89
2025 23 45 67 89
2030 23 45 67 89
2035 23 45 67 89

It’d be really nice if I could make the points in the same vertical line as the bar with the same header;

Advertisement

Answer

sns.scatterplot interprets the x-axis as numeric. As such, it doesn’t align well with a bar plot, nor does it have a dodge= parameter. You can use sns.stripplot instead.

Seaborn works easiest with its data in “long form”, which can be achieved via pandas pd.melt.

Here is some example code:

JavaScript

combining seaborn dodged bar plot with scatter plot

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement