[英]How to format the y- or x-axis labels in a seaborn FacetGrid
我想在 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' object has no attribute 'xaxis'
xaxis
和yaxis
是情節的屬性axes
,對於seaborn.axisgrid.FacetGrid
類型。
matplotlib.axes._subplots.AxesSubplot
lambda
表達式中的p
是刻度標簽編號。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'))
tkr.FuncFormatter
情況下也可以生成上一個圖。matplotlib.axis.Axis.set_major_formatter
# 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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.