python - 在 Seaborn Plot 中包装 xlabels
问题描述
一直在尝试修改我的情节,以便可以包装 xlabels。
看过类似问题的一些建议。
但我无法在此使用它们。
ax.set_xticklabels 代码不包装标签。
plt.xticks 代码引发错误 -
AttributeError: 'Text' object has no attribute 'expandtabs'
plt.figure(figsize = (7,5))
ax = sns.countplot(data = df3, x = df3.PaymentMethod, hue = df3.Churn)
#ax.set_xticklabels(ax.get_xticklabels(), ha="right", horizontalalignment = 'center', wrap = True)
plt.xticks([textwrap.fill(label, 10) for label in ax.get_xticklabels()],
rotation = 10, fontsize=8, horizontalalignment="center")
解决方案
textwrap
使用评论中建议的代码按预期工作:
import numpy as np # v 1.19.2
import pandas as pd # v 1.1.3
import seaborn as sns # v 0.11.0
import textwrap
# Create sample dataset
rng = np.random.default_rng(seed=1)
cat_names = ['Short name', 'Slightly longer name', 'Rather much longer name',
'Longest name of them all by far']
counts = rng.integers(10, 100, len(cat_names))
var_cat = np.repeat(cat_names, counts)
var_bool = rng.choice(['True', 'False'], size=len(var_cat))
df = pd.DataFrame(dict(vcat=var_cat, vbool=var_bool))
# Plot seaborn countplot with wrapped tick labels
ax = sns.countplot(data=df, x='vcat', hue='vbool')
labels = [textwrap.fill(label.get_text(), 12) for label in ax.get_xticklabels()]
ax.set_xticklabels(labels);
推荐阅读
- javascript - JSON Schema:是否有一个字段可以为字段指定元数据?
- flutter - Flutter:如何拉伸 Wrap Widget 中的最后一个元素?
- typescript - 如何在没有 cognito 的情况下使用 IAM_AUTH 调用 API Gateway 端点
- angular - Angular 10 PrimeNG 列表框项目上的条件咏叹调标签
- php - 我想知道如何对我的 php api 进行速率限制,以便 ip 或客户端无法使用 5 分钟
- azure - Azure VM 和 Visual Studio 代码
- python - 在 python 中更改 tkinter 的标签
- discord.js - QuickDB + Discordjs 'Gameboard' 固定消息系统不工作(类似于 Carl-Bot 的 'Starboard')
- sql - PL/SQL:光标将表中的最后一条记录加倍
- c# - 具有自定义属性的用户控件,例如 Grid.ColumnDefinitions