【问题标题】:Wrap xlabels in Seaborn Plot在 Seaborn Plot 中包装 xlabels
【发布时间】:2021-02-06 15:51:08
【问题描述】:

一直在尝试修改我的情节,以便可以包装 xlabels。
看过一些类似问题的建议。
但我无法在此使用它们。
ax.set_xticklabels 代码不包装标签。
plt.xticks 代码抛出错误 -
AttributeError: 'Text' 对象没有属性 '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 的绘图图像

【问题讨论】:

  • 可能是textwrap.fill(label.get_text(), 10)?标签本身是一个 matplotlib 对象,其中还包含颜色和位置信息。
  • 我想为绘图功能提供包装文本更容易(x=df3.PaymentMethod.apply(lambda x: textwrap.fill(x, 10))

标签: python matplotlib plot seaborn axis-labels


【解决方案1】:

textwrap 使用 cmets 中建议的代码按预期工作:

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

【讨论】:

    猜你喜欢
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    相关资源
    最近更新 更多