首页 > 解决方案 > 在 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")

具有重叠 xlabels 的绘图图像 在此处输入图像描述

标签: pythonmatplotlibplotseabornaxis-labels

解决方案


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);

textwrap_ticklabels


推荐阅读