You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

指定区域设置下格式化小数精度:解决Matplotlib坐标轴显示冲突

解决Matplotlib Y轴保留两位小数且用逗号作为小数分隔符的问题

你的问题出在FormatStrFormatter('%.2f')会直接使用Python原生格式化规则,忽略你设置的locale配置,所以小数分隔符还是点而非逗号。下面提供两种可行的解决方案:

方法一:用FuncFormatter结合locale格式化

通过自定义格式化函数,调用locale提供的格式化方法,既保留两位小数,又应用区域设置的分隔符:

import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import locale

# 配置巴西葡萄牙语区域
locale.setlocale(locale.LC_NUMERIC, 'pt_BR')
plt.rcParams['axes.formatter.use_locale'] = True

x = range(5)
y = range(5)

fig, ax = plt.subplots(constrained_layout=True, figsize=(8, 4))
ax.scatter(x, y)

# 自定义格式化函数,保留两位小数并应用locale规则
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: locale.format_string('%.2f', x)))

plt.show()

方法二:用StrMethodFormatter配合locale设置

StrMethodFormatter支持遵循locale配置的格式化规则,使用str.format语法即可实现需求:

import matplotlib.pyplot as plt
from matplotlib.ticker import StrMethodFormatter
import locale

locale.setlocale(locale.LC_NUMERIC, 'pt_BR')
plt.rcParams['axes.formatter.use_locale'] = True

x = range(5)
y = range(5)

fig, ax = plt.subplots(constrained_layout=True, figsize=(8, 4))
ax.scatter(x, y)

# StrMethodFormatter会自动应用locale的小数分隔符
ax.yaxis.set_major_formatter(StrMethodFormatter('{:.2f}'))

plt.show()

注意:如果你的系统未安装pt_BR区域包,可能会出现locale设置失败的情况,此时需要先在系统层面安装对应区域,或者手动替换小数点为逗号(但这种方式不如locale配置优雅)。

内容的提问来源于stack exchange,提问作者Raquel Aita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 20:10:09