How to prevent overlapping x-axis labels in sns.countplot

william007 picture william007 · Mar 1, 2017 · Viewed 52.6k times · Source

For the plot

sns.countplot(x="HostRamSize",data=df)

I got the following graph with x-axis label mixing together, how do I avoid this? Should I change the size of the graph to solve this problem?

enter image description here

Answer

ImportanceOfBeingErnest picture ImportanceOfBeingErnest · Mar 8, 2017

Having a Series ds like this

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(136)

l = "1234567890123"
categories = [ l[i:i+5]+" - "+l[i+1:i+6] for i in range(6)]
x = np.random.choice(categories, size=1000, 
            p=np.diff(np.array([0,0.7,2.8,6.5,8.5,9.3,10])/10.))
ds = pd.Series({"Column" : x})

there are several options to make the axis labels more readable.

Change figure size

plt.figure(figsize=(8,4)) # this creates a figure 8 inch wide, 4 inch high
sns.countplot(x="Column", data=ds)
plt.show()

Rotate the ticklabels

ax = sns.countplot(x="Column", data=ds)

ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
plt.tight_layout()
plt.show()

enter image description here

Decrease Fontsize

ax = sns.countplot(x="Column", data=ds)

ax.set_xticklabels(ax.get_xticklabels(), fontsize=7)
plt.tight_layout()
plt.show()

enter image description here

Of course any combination of those would work equally well.

Setting rcParams

The figure size and the xlabel fontsize can be set globally using rcParams

plt.rcParams["figure.figsize"] = (8, 4)
plt.rcParams["xtick.labelsize"] = 7

This might be useful to put on top of a juypter notebook such that those settings apply for any figure generated within. Unfortunately rotating the xticklabels is not possible using rcParams.

I guess it's worth noting that the same strategies would naturally also apply for seaborn barplot, matplotlib bar plot or pandas.bar.