0
votes

I'm trying to plot a seaborn countplot that has very long x-values that are literally sentences. So instead of inserting them under xticks, I thought it might be better to use hue parameter of countplot and put the labels in the legend. But this produces extremely thin bars that are far apart from each other (see example below), when I wanted the bars to be what it would be if I didn't assign anything to the hue parameter. How do I fix this?

Example:

df0 = pd.DataFrame({'col':['This is a very long string. So yeah, there you have it, a long, long string.', 
                           'What, you egg? said William Shakespeare.', 
                           'OK, this is now getting out of hand.']})
seaborn.countplot(df0['col'], hue=df0['col'])
plt.legend(loc='upper left', bbox_to_anchor=(1, 1))

This code produces

enter image description here

My desired graph:

enter image description here

2

2 Answers

2
votes

According to: http://seaborn.pydata.org/generated/seaborn.countplot.html#seaborn.countplot

you need to add dodge=False to your call to countplot

dodge : bool, optional

When hue nesting is used, whether elements should be shifted along the categorical axis.

seaborn.countplot('col', hue='col', dodge=False, data=df0)
1
votes

To fix the labels from overlapping, you can rotate them a bit. I also used the dodge option to address the size of the bar. Seaborn does not have an effective way to wrap text so you have to decide to rotate it or eliminate it completely.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df0 = pd.DataFrame({'col':['This is a very long string. So yeah, there you have it, a long, long string.', 
                           'What, you egg? said William Shakespeare.', 
                           'OK, this is now getting out of hand.']})
ax = sns.countplot(df0['col'], hue=df0['col'],dodge=False)
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
plt.legend(loc='upper left', bbox_to_anchor=(1, 1))
plt.tight_layout()
plt.show()

Output is:

enter image description here

I tweaked it a bit and got this. Also set ax.set_xticklabels('') to remove the labels from the x axis.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df0 = pd.DataFrame({'col':['This is a very long string. So yeah, there you have it, a long, long string.', 
                           'What, you egg? said William Shakespeare.', 
                           'OK, this is now getting out of hand.']})
ax = sns.countplot(df0['col'], hue=df0['col'],dodge=False)
ax.set_xticklabels('')
#ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
plt.legend(loc='lower center', bbox_to_anchor=(1, 1))
plt.tight_layout()
plt.show()

The output is:

enter image description here