如何在seaborn FacetGrid中格式化y轴或x轴标签

8
我想在seaborn FacetGrid图中格式化y轴标签,包括小数位数和/或一些文本。
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks")

exercise = sns.load_dataset("exercise")

g = sns.catplot(x="time", y="pulse", hue="kind", col="diet", data=exercise)
#g.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:,.2f}'.format(x) + 'K'))
#g.set(xticks=['a','try',0.5])
g.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:,.2f}'.format(x) + 'K'))
plt.show()

受启发于 如何将 seaborn/matplotlib 轴标记格式从数字转换为千位或百万位?(125,436 变成 125.4K)
ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:,.2f}'.format(x) + 'K'))

下面的错误提示信息如下:

AttributeError: 'FacetGrid'对象没有属性'xaxis'

1个回答

17
  • xaxisyaxis是绘图axes的属性,适用于seaborn.axisgrid.FacetGrid类型。
    • 在链接的答案中,该类型为matplotlib.axes._subplots.AxesSubplot
  • plambda表达式中是刻度标签的数字。
  • seaborn: 构建结构化多面板网格
  • matplotlib: 创建多个子图
  • 已测试并可与以下版本正常工作:
    • matplotlib v3.3.4
    • seaborn v0.11.1
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr

sns.set(style="ticks")

# load data
exercise = sns.load_dataset("exercise")

# plot data
g = sns.catplot(x="time", y="pulse", hue="kind", col="diet", data=exercise)

# format the labels with f-strings
for ax in g.axes.flat:
    ax.yaxis.set_major_formatter(tkr.FuncFormatter(lambda y, p: f'{y:.2f}: Oh baby, baby'))
    ax.xaxis.set_major_formatter(tkr.FuncFormatter(lambda x, p: f'{x}: Is that your best'))

在这里输入图片描述

# format the labels with f-strings
for ax in g.axes.flat:
    ax.yaxis.set_major_formatter(lambda y, p: f'{y:.2f}: Oh baby, baby')
    ax.xaxis.set_major_formatter(lambda x, p: f'{x}: Is that your best')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接