python - 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
解决方案
正如@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()
会显示更多类似的东西
推荐阅读
- c# - Unity MobAd 奖励视频无法正常工作
- python - 与 ImageDataGenerator 一起使用时,Keras Resnet50 preprocess_input 会出现灰度图像错误
- git - 在 Git 存储库之间共享 Nuget.config
- c# - 遍历 JSON?
- java - Dagger2:如何在不注入合成器类的情况下注入字段?
- vue.js - vuetify 表自定义排序“TypeError:无法读取未定义的属性'过滤器'”
- spring-boot - Windows 上的 Spring Boot 应用程序中的 kerberos iis 身份验证问题
- javascript - 从仅出现一次的链接中查找完全匹配的字母
- java - 如何根据相应的行将jTable值插入数据库?
- c# - 从上午 07:00 开始每 8 小时运行一次 Quartz.NET 以执行特定作业