如何在 seaborn FacetGrid 中格式化 y 轴或 x 轴标签 [英] How to format the y- or x-axis labels in a seaborn FacetGrid

查看:124
本文介绍了如何在 seaborn FacetGrid 中格式化 y 轴或 x 轴标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 seaborn FacetGrid 图中格式化 y 轴标签,带有多个小数和/或添加一些文本.

导入 seaborn 为 sns导入 matplotlib.pyplot 作为 pltsns.set(style="ticks")运动 = sns.load_dataset(运动")g = sns.catplot(x=时间",y=脉冲",色调=种类",col=饮食",数据=运动)#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()

灵感来自

# 用 f-strings 格式化标签对于 g.axes.flat 中的 ax: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')

I want to format y-axis labels in a seaborn FacetGrid plot, with a number of decimals, and/or with some text added.

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()

Inspired from How to format seaborn/matplotlib axis tick labels from number to thousands or Millions? (125,436 to 125.4K)

ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:,.2f}'.format(x) + 'K'))

It results in the following error.

AttributeError: 'FacetGrid' object has no attribute 'xaxis'

解决方案

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')

这篇关于如何在 seaborn FacetGrid 中格式化 y 轴或 x 轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆