让我们考虑以下示例(来自 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)
输出:
我想更改 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}'))
这是输出:
看起来 x
与 lambda
中的 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.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
关于python - 如何为 seaborn catplot 的每个子图自定义文本标记标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69810007/