Maverick Meerkat
Maverick Meerkat

Reputation: 6424

seaborn: countplot rotation and formatting to decimal places

I'm trying to both rotate (45 degrees) and narrow the xticks (to 2 decimal places) of my countplot in seaborn. But unfortunately I can't get it to work.

This is my code:

from matplotlib.ticker import FormatStrFormatter
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

wine_data = pd.read_csv('winequality-white.csv', sep=';')
fig, ax1 = plt.subplots(figsize=(15,5))
ax1.xaxis.set_tick_params(rotation=45)
ax1.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))
sns.countplot(data=wine_data, x='alcohol', ax=ax1)

You can download the data-set here.

And this is the result: enter image description here

As you can see rotation works, but the formatting doesn't.

Upvotes: 2

Views: 4714

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40737

Are you sure countplot() is the right kind of plot for your data? countplot is meant to be used with categorical data, whereas "alcohol content" is a continuous value. Seems to me you are trying to plot a histogram, or sns.distplot() if you really want to use seaborn?

In any case, your problem stems from the fact that it is a categorical plot, and therefore each tick represent a category as a string, and not as a float as you would expect given your data. To fix the rounding of the numbers, you therefore need to extract those string, convert them back into numbers and round them as you convert them back again in strings...

fig, ax1 = plt.subplots(figsize=(10,4))
sns.countplot(data=wine_data, x='alcohol', ax=ax1)
ax1.set_xticklabels(['{:.2f}'.format(float(t.get_text())) for t in ax1.get_xticklabels()])
ax1.xaxis.set_tick_params(rotation=45)

enter image description here

Upvotes: 2

Related Questions