python - 如何为 seaborn catplot 的每个子图自定义文本标记标签

标签 python matplotlib seaborn facet-grid catplot

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

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)

输出:

enter image description here

我想更改 y 轴上的刻度标签,例如在括号中添加一个数字:(1) Southampton,(2) Cherbourg,(3) Queenstown。我看过这个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}'))

这是输出:

enter image description here

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


软件版本:

matplotlib                         3.4.3
seaborn                            0.11.2

最佳答案

  • 类似于 How to rotate xticklabels in a seaborn catplot 的答案,但需要为每个子图的每个刻度定制文本。
  • 文本标签的工作方式与另一个示例中的数字标签不同。数字标签与刻度位置匹配,但文本标签并非如此。
  • .get_yticklabels() 获取 [Text(0, 0, 'Southampton'), Text(0, 1, 'Cherbourg'), Text(0, 2, 'Queenstown' )] 每个子图
  • 如下图,提取文字和位置,使用.set_yticklabels设置新的文字标签
  • python 3.8.12matplotlib 3.4.3seaborn 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

enter image description here

关于python - 如何为 seaborn catplot 的每个子图自定义文本标记标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69810007/

相关文章:

python - 如何使用 pandas 创建具有条件日期时间的新列

python - 如何为自动生成的 OneToOneField 关系设置默认值?

python - 使用 Python 从列的每一行中的字符串中切片子字符串

Python线程: Queue workers - hang the program

python - Seaborn Violinplot 更改色调顺序

python - 如何在seaborn中将matplotlib颜色图设置为调色板

python - Barplot savefig() 返回一个 AttributeError

python - 如何更改 matplotlib 图例框中的名称?

python - 来自堆叠数据帧的 fill_between

python - 绘制 pandas 聚合对象