60

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

ImportanceOfBeingErnest
  • 289,005
  • 45
  • 571
  • 615
william007
  • 15,661
  • 20
  • 90
  • 161

5 Answers5

96

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.

ImportanceOfBeingErnest
  • 289,005
  • 45
  • 571
  • 615
  • `AttributeError: 'FacetGrid' object has no attribute 'get_xticklabels'` when trying to rotate the ticklabels. – PlsWork Jan 26 '20 at 23:43
  • @AnnaVopureta I didn't claim this works with a FacetGrid. It works with any seaborn function that returns an axes. – ImportanceOfBeingErnest Jan 26 '20 at 23:44
  • It fails when I use it for the following seaborn function that returns an axis: `ax = sns.catplot(y="Dataset", x="Size (bytes)", hue="Implementation", data=pdData, height=6, kind="bar", palette="muted", legend=False)` – PlsWork Jan 26 '20 at 23:46
  • 1
    I know. Because catplot returns a FacetGrid, not an axes. – ImportanceOfBeingErnest Jan 26 '20 at 23:47
  • I wasn't aware of that, my bad. How to solve the overlapping axis labels problem for catplot (and other functions that return FacetGrid)? – PlsWork Jan 26 '20 at 23:47
  • Here is one way to do it: `for axes in ax.axes.flat: axes.set_xticklabels(axes.get_xticklabels(), rotation=65, horizontalalignment='right')` Solution is described here: https://www.drawingfromdata.com/how-to-rotate-axis-labels-in-seaborn-and-matplotlib – PlsWork Jan 26 '20 at 23:53
13

You can rotate the x_labels and increase their font size using the xticks methods of pandas.pyplot.

For Example:

import matplotlib.pyplot as plt
plt.figure(figsize=(10,5))
chart = sns.countplot(x="HostRamSize",data=df)

plt.xticks(
    rotation=45, 
    horizontalalignment='right',
    fontweight='light',
    fontsize='x-large'  
)

For more such modifications you can refer this link: Drawing from Data

Deepam Gupta
  • 1,714
  • 1
  • 18
  • 29
  • 1
    You are a genius! This is the best answer that I have seen that does **not** rely on the `ax.set_xticklabels(ax.get_xticklabels(), fontsize=7)` method. THANK YOU! – shadow_dev Aug 04 '20 at 15:56
8

If you just want to make sure xticks labels are not squeezed together, you can set a proper fig size and try fig.autofmt_xdate().

This function will automatically align and rotate the labels.

hui chen
  • 714
  • 10
  • 14
3

I don't know whether it is an option for you but maybe turning the graphic could be a solution (instead of plotting on x=, do it on y=), such that:

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

enter image description here

Carles S
  • 2,388
  • 10
  • 23
2
plt.figure(figsize=(15,10)) #adjust the size of plot
ax=sns.countplot(x=df['Location'],data=df,hue='label',palette='mako')

ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")  #it will rotate text on x axis

plt.tight_layout()
plt.show()

you can try this code & change size & rotation according to your need.

Akash Desai
  • 430
  • 5
  • 10
  • Please don't post code-only answers. For future readers, it's far more interesting to see explained why this answers the question. And answers with explanations tend to have better acceptance. – Akif Nov 14 '20 at 09:32