Search code examples
seabornspyderx-axis

Spacing x-axis based on values in a column using seaborn in spyder


I am using seaborn to generate a boxplot of 5 different conditions and their corresponding values. I want the x-axis values to be plotted in the correct distance from each other based on their actual values instead of evenly spaced out boxplots. I have a large data set but to simplify my question I made up some numbers with a smaller data set. I have the following code:

dff=pd.DataFrame()
dff['Concentration']=[150,150,150,150,300,300,300,300,525,525,525,525,600,600,600,600,650,650,650,650]
dff['Counts']=[0.677,0.703,0.800,0.705,1.0,0.906,1.11,0.877,1.255,1.38,1.25,1.38,1.4,1.5,1.6,1.667,1.65,1.66,1.70,1.599]

figxyz,ax=plt.subplots(1,1,figsize=(4,4))
sns.boxplot(dff['Concentration'],dff['Counts'],color='tan')
sns.swarmplot(dff['Concentration'],dff['Counts'],color='black')

I get the following boxplot. I want the distance between concentrations to correspond to the distance between the actual numbers. For example, the distance between 150 and 300 boxplots should be smaller than the distance between 300 and 525 and the smallest distance should be between 600 and 650.

I also tried using the following code and it seems to move the x-ticks but clusters the boxplots all the way the the left like this.

ax.set_xticks(dff['Concentration']) 

Solution

  • You may have to use matplotlib's boxplot() instead of seaborn's:

    data = {k:v.values for k,v in dff.groupby('Concentration')['Counts']}
    
    fig, ax = plt.subplots()
    ax.boxplot(x=data.values(), positions=list(data.keys()), widths=50, sym='')
    ax.plot(dff['Concentration'],dff['Counts'],'o')
    

    enter image description here