【问题标题】:Use locale with seaborn使用带有 seaborn 的语言环境
【发布时间】:2018-10-01 11:37:44
【问题描述】:

目前我正在尝试可视化我正在使用 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)

【问题讨论】:

  • 试过类似的东西(见this答案)。不幸的是,这也不起作用。
  • 这对我来说似乎不是一个海上问题。虽然使用plt.plot 愉快地根据所选语言环境格式化其标签,但通过plt.boxplot(df.T, positions=list(df.columns)) 直接调用matplotlib 函数会忽略语言环境。所以在我看来,这是由于 positions 关键字在 matplotlib 中的处理方式。
  • 在没有真正解决根本问题的情况下,获取 x 轴上带逗号的数字的愚蠢方法是将 df.columns 设置为适当的字符串:df.columns = ["0,3", "0,7"]
  • @jdamp 很不幸。似乎最快和最简单的方法是将数字转换为适当的字符串。谢谢!
  • @jdamp seaborn 宁愿调用类似plt.boxplot(df.T, positions=range(len(df.columns)), labels=df.columns) 的东西,所以这里相关的不是位置,而是标签。此外,分析非常正确。

标签: python python-3.x matplotlib seaborn


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-03-07
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多