对seaborn使用语言环境

时间:2018-10-01 11:37:45

标签: python python-3.x matplotlib seaborn

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

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

以下是一些示例性数据。请注意,我必须使用'german'而不是"de_DE"。所有xlabel都使用标准点作为小数点分隔符。

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

1 个答案:

答案 0 :(得分:2)

在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