Setting xticks in sns.swarmplot

2k Views Asked by At

I have some problems with setting xticks in swarmplot and pointplot in seaborn (though with traditional plt.plot it's OK). When I use typical commands like:

plt.xticks([2,3,4,5,6,7,8])

or:

ax2.xaxis.set_major_locator(ticker.LinearLocator(8))

xticks are only in a short range which doesn't cover the whole x axis. https://i.stack.imgur.com/H1D5Q.jpg

enter image description here

(left subplot on the image). When I dont't type plt.xticks(... then I get something like on the right subplot.

My code is here:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

df = pd.read_csv('dane/iris.csv')
df['Legend'] = df['variety']
df['variety'].replace( {'Setosa':1, 'Versicolor':2, 'Virginica':3}, inplace = True)

fig = plt.figure(figsize = (13,7), facecolor = 'white')

ax1 = fig.add_subplot(1,2,1)
sns.swarmplot(df['sepal.length'], df['sepal.width'], hue = df['Legend'], ax = ax1)
plt.xlabel('Sepal length', fontsize = 14)
plt.ylabel('Sepal width', fontsize = 14)
plt.xticks([])
plt.xticks([2,3,4,5,6,7,8])

ax2 = fig.add_subplot(122)
sns.swarmplot(df['petal.length'], df['petal.width'], hue = df['Legend'], ax = ax2)
plt.xlabel('Petal length', fontsize = 14)
plt.ylabel('Petal width', fontsize = 14)

plt.savefig(Figure = fig, fname = 'iris.png')
1

There are 1 best solutions below

1
On BEST ANSWER

swarmplot is a categorical plot. It plots categories on the x axis. Using plt.xticks([2,3,4,5,6,7,8]) you are setting ticks for the categories 2 to 8, but you have many more categories in your plot.

For the data in use it does not look like a categorical plot is actually much of use. You may rather use a scatter plot, which is a numerical plot in both dimensions.

You may use ax.scatter() or sns.scatterplot() instead.