如何用seaborn处理长轴标签?

时间:2017-07-10 13:42:44

标签: python-3.x graph seaborn axis-labels

我用seaborn制作了一些图表。我通过某些团体绘制箱形图和其他东西。我举一个例子来说明:

enter image description here

正如您所看到的,x-lables太长了。我将它们旋转90度只是为了让它们可读。我可以手动更改类别名称。但是,我需要每周执行此任务 - 类别会随着时间的推移而变化。你有什么好主意如何解决这个问题?

为了好的衡量,我会告诉你到目前为止我所做的一切。给定一个可能的数据集,这基本上就是我对我的pandas数据帧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()

有没有办法在没有丢失信息的情况下剥离长x轴标签?我的想法是将标签保留在图例中。也许类似于这个例子?这是可能的seaborn,如果是这样的话?

enter image description here

有什么想法吗?非常感谢你提前!

1 个答案:

答案 0 :(得分:3)

当然,您可以尝试通过翻转xy

来水平制作箱形图
ax =sns.boxplot(y='category', x=sentiment, data=df);

您还可以生成一个自定义图例,在其中使用每个箱图的颜色设置补丁

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)

long labels to legend