【问题标题】:How to handle long axis labels with seaborn?如何使用 seaborn 处理长轴标签?
【发布时间】:2017-12-14 06:46:37
【问题描述】:

我有几张用seaborn 制作的图表。我按某些组绘制箱线图和其他东西。我举个例子来说明:

如您所见,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 有可能吗?如果可以,怎么做?

有什么想法吗?非常感谢您!

【问题讨论】:

  • 问题是,您希望这些图看起来如何?在不知道的情况下,我们应该如何提供帮助?
  • 你说得有道理。我有几个想法。然而,我也对其他任何事情持开放态度。我将相应地编辑我的问题。谢谢你!

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


【解决方案1】:

当然,您可以尝试通过翻转x 和y 来水平制作箱线图

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)

【讨论】:

  • 绝对是个好建议。但它并没有解决“长字符串”问题。有任何想法吗?到目前为止,我只是将它们缩写。但这也不好。
  • 已编辑答案,包括将长标签放入自定义图例中。另请参阅this great answer,了解如何通过精细控制(您需要)放置图例
猜你喜欢
  • 2021-01-01
  • 2011-06-03
  • 2015-10-16
  • 2017-08-02
  • 2015-12-19
  • 2020-08-05
  • 1970-01-01
  • 2020-12-21
  • 2020-10-21
相关资源
最近更新 更多