I have a few graphs I made with seaborn
. I plot boxplots and other things by certain groups. I'll give you an example to illustrate:
As you can see, the x-lables are too long. I rotated them by 90 degrees just to make them readable. I could go and change the category names manually. However, I need to perform this task weekly - and the categories change over time. Do you have any good idea how to solve this issue?
For good measure, I'll give you what I have done so far. Given a figitive dataset, this is basically what I do with my pandas dataframe df
:
rank sentiment category
0 1 0.657413 super_long_string
1 2 0.895769 super_long_string
2 3 -0.435457 super_long_string
3 4 -0.717959 other_super_long_string
4 5 0.869688 other_super_long_string
ax =sns.boxplot(x='category', y=sentiment, data=df);
ax.set_xticklabels(ax.get_xticklabels(),rotation=90)
plt.figure()
Is there a way to strip a way the long x-axis lables without losing the info? My idea is to keep the labels in a legend. Maybe similar to this example? Is that possible with seaborn, and if so how?
Any ideas? Thank you very much in advance!
well of course you could try to make the boxplots horizontally by flipping the x
and y
ax =sns.boxplot(y='category', x=sentiment, data=df);
you could also generate a custom legend in which you set a patch with the color of each of your boxplots
import pandas as pd
import seaborn.apionly as sns
import scipy as sp
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
labels = ['this is some really really long label text, so long that it is much better read horizontally',
'and another really long label, this could probably be very much reduced',
'a short label for a change',
'lorem ipsum',
'and another really long and very descriptive label, including some abbreviations a.n.g']
Df = pd.DataFrame(sp.randn(len(labels),10))
Df['labels'] = labels
fig, ax = plt.subplots()
ax = sns.boxplot(data=Df.melt(id_vars='labels'),x='labels',y='value',ax=ax)
ax.set_xticklabels('')
leg_handles = []
for label,artist in zip(labels,ax.artists):
handle = mpatches.Patch(facecolor=artist.get_facecolor(),label=label)
leg_handles.append(handle)
ax.legend(handles=leg_handles,bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=1, mode="expand", borderaxespad=0.)
fig.subplots_adjust(top=0.75)