【问题标题】:Seaborn facetgrid add commas to y axis labels [duplicate]Seaborn facetgrid将逗号添加到y轴标签[重复]
【发布时间】:2020-11-27 15:41:19
【问题描述】:

我目前有这个图表,使用以下方法创建:

fg = sns.catplot(x='metric', y='number', hue='drop', data=df, kind='bar')

我需要将轴标签更改为逗号。

我试过了:

df['number'] = df['number'].apply(lambda x: "{:,}".format(x))

但是这个错误,因为 x 或 y 值都不是数字(上面将数据类型从数字更改为对象)。

如何在 y 轴值中获取逗号?

我不能使用 get_yaxis().set_major_formatter 因为这不是 facetgrid 的属性。

【问题讨论】:

  • 仅供参考,您可以使用 fg.axes 获取坐标区对象,如图所示 here

标签: python seaborn bar-chart visualization


【解决方案1】:

以下代码中的 for 循环使用 StrMethodFormatter 创建逗号格式。

import matplotlib.pyplot as plt
from matplotlib.ticker import StrMethodFormatter
import matplotlib.ticker as ticker
import pandas as pd
import seaborn as sns

#Theme
sns.set(style="darkgrid")

#Example data frame
df = pd.DataFrame()
df["Value"]    = [1000000, 2000000, 3000000, 2000000, 5000000] 
df["Category"] = ["A","B","C","D","E"]
fg = sns.catplot(x='Category', y='Value', data=df, kind='bar')

for ax in fg.axes.flat:
    ax.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))

#So that axis show
plt.tight_layout()

#Show plot
plt.show()

【讨论】:

    猜你喜欢
    • 2022-06-14
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多