gpt4 book ai didi

python - 在 seaborn 中使用语言环境

转载 作者:太空宇宙 更新时间:2023-11-03 11:15:29 27 4
gpt4 key购买 nike

目前,我正在尝试可视化我正在使用 seaborn 处理的一些数据。我需要使用逗号作为小数点分隔符,所以我在考虑简单地更改语言环境。我找到了 this回答类似的问题,它设置语言环境并使用 matplotlib 绘制一些数据。

这对我也适用,但是当直接使用 seaborn 而不是 matplotlib 时,它不再使用语言环境。不幸的是,我找不到任何可以更改 seaborn 或任何其他解决方法的设置。有办法吗?

这里有一些示例性数据。请注意,我必须使用 'german' 而不是 "de_DE"。 xlabels均使用标准点作为小数点分隔符。

import locale
# Set to German locale to get comma decimal separator
locale.setlocale(locale.LC_NUMERIC, 'german')

import pandas as pd
import seaborn as sns

import matplotlib.pyplot as plt
# Tell matplotlib to use the locale we set above
plt.rcParams['axes.formatter.use_locale'] = True

df = pd.DataFrame([[1,2,3],[4,5,6]]).T
df.columns = [0.3,0.7]

sns.boxplot(data=df)

Exemplary boxplot with seaborn

最佳答案

此类箱线图的 x 轴上显示的“数字”是通过matplotlib.ticker.FixedFormatter(通过 print(ax.xaxis.get_major_formatter()) 找到)。这个固定的格式化程序只是将标签从标签列表中一个一个地放在刻度上。这是有道理的,因为您的框位于 01,但您希望它们被标记为 0.30.7。我想当考虑使用 df.columns=["apple","banana"] 的数据帧应该发生什么时,这个概念会变得更加清晰。

所以 FixedFormatter 忽略了语言环境,因为它只是按原样使用标签。我在这里提出的解决方案(尽管评论中的一些同样有效)是自己格式化标签。

ax.set_xticklabels(["{:n}".format(l) for l in df.columns]) 

此处的n 格式与通常的g 格式相同,但考虑了语言环境。 (参见 python format mini language)。当然,使用任何其他选择的格式同样是可能的。另请注意,通过 ax.set_xticklabels 在此处设置标签仅适用于箱线图使用的固定位置。对于具有连续轴的其他类型的图,不建议这样做,而是应使用链接答案中的概念。

完整代码:

import locale
# Set to German locale to get comma decimal separator
locale.setlocale(locale.LC_NUMERIC, 'german')

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame([[1,2,3],[4,5,6]]).T
df.columns = [0.3,0.7]

ax = sns.boxplot(data=df)
ax.set_xticklabels(["{:n}".format(l) for l in df.columns])

plt.show()

enter image description here

关于python - 在 seaborn 中使用语言环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52590247/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com