如何为seaborn catplot的每个子图自定义文本刻度标签

问题描述 投票:0回答:2

让我们考虑以下示例(来自 Seaborn 文档):

titanic = sns.load_dataset("titanic")

fg = sns.catplot(x="age", y="embark_town",
                hue="sex", row="class",
                data=titanic[titanic.embark_town.notnull()],
                orient="h", height=2, aspect=3, palette="Set3",
                kind="violin", dodge=True, cut=0, bw=.2)

输出:

我想更改 y 轴上的刻度标签,例如通过在括号中添加数字:(1) 南安普敦,(2) 瑟堡,(3) 皇后镇。我看过这个answer,并且尝试使用

FuncFormatter
,但我得到了一个奇怪的结果。这是我的代码:

titanic = sns.load_dataset("titanic")

fg = sns.catplot(x="age", y="embark_town",
                hue="sex", row="class",
                data=titanic[titanic.embark_town.notnull()],
                orient="h", height=2, aspect=3, palette="Set3",
                kind="violin", dodge=True, cut=0, bw=.2)

from matplotlib.ticker import FuncFormatter
for ax in fg.axes.flat:
    ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: f'({1 + pos}) {x}'))

这是输出:

看起来

x
pos
中的
lambda
相同。我期望
x
是刻度标签的值(即南安普敦、瑟堡、皇后镇)。我做错了什么?


软件版本:

matplotlib                         3.4.3
seaborn                            0.11.2
python matplotlib seaborn facet-grid catplot
2个回答
3
投票
  • 类似于如何在seaborn catplot中旋转xticklabels的答案,但需要为每个子图的每个刻度自定义文本。
  • 文本标签的工作方式与其他示例中的数字标签不同。数字标签与刻度位置匹配,但文本标签并非如此。
  • 每个子图
  • .get_yticklabels()
    都会获得
    [Text(0, 0, 'Southampton'), Text(0, 1, 'Cherbourg'), Text(0, 2, 'Queenstown')]
  • 如下图,提取文字和位置,使用
    .set_yticklabels
    设置新的文字标签
  • 已在
    python 3.8.12
    matplotlib 3.4.3
    seaborn 0.11.2
  • 进行测试
import seaborn as sns

titanic = sns.load_dataset("titanic")

fg = sns.catplot(x="age", y="embark_town",
                hue="sex", row="class",
                data=titanic[titanic.embark_town.notnull()],
                orient="h", height=2, aspect=3, palette="Set3",
                kind="violin", dodge=True, cut=0, bw=.2)

for ax in fg.axes.flat:  # iterate through each subplot
    labels = ax.get_yticklabels()  # get the position and text for each subplot
    for label in labels:
        _, y = label.get_position()  # extract the y tick position
        txt = label.get_text()  # extract the text
        txt = f'({y + 1}) {txt}'  # update the text string
        label.set_text(txt)  # set the text
    ax.set_yticklabels(labels)  # update the yticklabels


0
投票

以及我如何将每个年龄值绘制到每个子图,而不仅仅是底部一个?

© www.soinside.com 2019 - 2024. All rights reserved.