让我们考虑以下示例(来自 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
.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
以及我如何将每个年龄值绘制到每个子图,而不仅仅是底部一个?