首页 > 解决方案 > Seaborn:有没有更好的方法将文本包裹在我的条形图中?

问题描述

我正在为条形图编写函数,但遇到了另一个小问题。我有一些 ytick 标签太长,导致无法看到我的 y 轴标签。当我大幅减小 ytick 标签的大小时,我只能看到 y 标签。

def bar_plot(data, x, y, title):
    sns.set_style('darkgrid')
    data = data.sort_values(ascending=False, by=x)
    data = data.head(n=10)
    if (data[x]>1000000).any():
        data[x] = data[x] / 1000000
        ax = sns.barplot(data=data, x=x, y=y)
        ax.set_title(title, size=35)
        ax.set_xlabel(x + ' ($ Millions)', size=15)
        ax.set_ylabel(y, size=15)
        ax.set_yticklabels(data[y].head(n=10), wrap=True)

    else:
       ax = sns.barplot(data=data, x=x, y=y)
       ax.set_xlabel(x, size=15)
       ax.set_ylabel(y, size=15)
       ax.set_title(title, size=35)
       ax.set_yticklabels(data[y].head(n=10), wrap=True)

我试图ax.set_yticklabels(data[y].head(n=10), wrap=True)包装文本。虽然它有效,但它对文本的包装不够。有没有办法告诉wrap=True在 x 个字符后换行?我试过用谷歌搜索,但找不到任何有用的东西。

编辑

我正在使用的数据框的格式类似于

Client Name            Col 1      Col 2      Col 3      Col 4       Col 5
Some name              51,235.00  nan        23,423.00  12,456.00   654.00
Some long company name 152.00     5,626.00   nan        82,389.00   5,234.00
Name                   12,554.00  5,850.00   1,510.00   nan         12,455.00
Company                12,464.00  nan        752.00     1,243.00    1,256.00
Long Company Name      12,434.00  78,915.00  522.00     2,451.00    6,567.00

标签: pythonmatplotlibdata-visualizationseabornword-wrap

解决方案


正如@ImportanceOfBeingErnest指出的那样,您可以使用该textwrap模块来执行此操作,特别有用的是textwrap.fill()

textwrap.fill(text[, width[, ...]])

将单个段落包装在文本中,因此每行最多为width字符长,并返回包含包装段落的单个字符串。fill()是简写

"\n".join(wrap(text, ...))

尽管您需要在每个标签上分别调用它,例如

ax.set_yticklabels([textwrap.fill(e, width) for e in data[y].head()])

编辑

这是一个更完整的示例来显示用法:

import textwrap
import matplotlib.pyplot as plt
import pandas as pd

df = {'Client Name': ['Some Name', 'Some long company name', 'Name',
            'Company', 'Long Comany Name'],
      'Col 1': [51235, 152, 12554, 12464, 12434]}
data = pd.DataFrame(df)

fig, ax = plt.subplots(1)


ax.set_yticklabels(data['Client Name'].head())
plt.show()

这将显示以下内容

在此处输入图像描述

然而

ax.set_yticklabels([textwrap.fill(e, 7) for e in data['Client Name'].head()])
plt.show()

会显示更多类似的东西

在此处输入图像描述


推荐阅读