如何在使用特定语言环境的小数分隔符时格式化小数精度?

huangapple go评论79阅读模式
英文:

How can I format decimal precision when using a specific locale for the decimal separator?

问题

需要在y轴上保留两位小数精度绘制图表。目前,我正在使用ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))来实现这一点。

但现在,我需要以逗号作为小数分隔符来显示数字。当我使用locale来更改此设置时,例如locale.setlocale(locale.LC_NUMERIC, 'pt_BR')plt.rcParams['axes.formatter.use_locale'] = True,它会被覆盖,因为我指定了小数位数。

这是我使用的代码:

import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

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)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
plt.show()

如何在使用特定语言环境的小数分隔符时格式化小数精度?


[1]: https://i.stack.imgur.com/MY4HM.png

<details>
<summary>英文:</summary>

I need to plot a graph that has 2 decimal places of precision in the y axis. Currently, I am using `ax.yaxis.set_major_formatter(FormatStrFormatter(&#39;%.2f&#39;))` to do that.

But now, I need to display the numbers with comma as the decimal separator. When I use `locale` to change the setting for that with `locale.setlocale(locale.LC_NUMERIC, &#39;pt_BR&#39;)` and `plt.rcParams[&#39;axes.formatter.use_locale&#39;] = True`, it gets overwritten as I specify the number of decimal places. 

This is the code that I used:

import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

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)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
plt.show()

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/MY4HM.png

</details>


# 答案1
**得分**: 1

Here is the translated content:

"你的代码存在两个问题:

1. `&#39;%.2f&#39;` 不会受到区域设置的影响,它是独立于区域的。你需要使用 `locale.format_string()` 来处理它。
2. 使用 `FuncFormatter` 而不是 `FormatStrFormatter`。

类似这样的代码:

```py
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import locale
locale.setlocale(locale.LC_NUMERIC, &#39;pt_BR&#39;)
plt.rcParams[&#39;axes.formatter.use_locale&#39;] = True

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

fig, ax = plt.subplots(constrained_layout=True, figsize=(8, 4))
ax.scatter(x, y)
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: locale.format_string(&#39;%.1f&#39;, x)))
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: locale.format_string(&#39;%.2f&#39;, x)))
plt.show()

如何在使用特定语言环境的小数分隔符时格式化小数精度?

这里有一些在不需要精度的情况下使用区域设置格式化字符串的示例。

英文:

Two issues with your code:

  1. &#39;%.2f&#39; does not interact with locale settings, it is locale independent. You need to use locale.format_string() with it.
  2. Use FuncFormatter rather than FormatStrFormatter

Something like:

import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import locale
locale.setlocale(locale.LC_NUMERIC, &#39;pt_BR&#39;)
plt.rcParams[&#39;axes.formatter.use_locale&#39;] = True

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

fig, ax = plt.subplots(constrained_layout=True, figsize=(8, 4))
ax.scatter(x, y)
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: locale.format_string(&#39;%.1f&#39;, x)))
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: locale.format_string(&#39;%.2f&#39;, x)))
plt.show()

如何在使用特定语言环境的小数分隔符时格式化小数精度?

Some examples of using locale formatted strings when precision isn't required.

答案2

得分: 0

It looks like FormatStrFormatter() 不考虑 set_locale() 并使用默认的 .,从而覆盖了格式。所以,您可以获取标签,在末尾添加零... 更新了下面的代码。希望这有所帮助...

import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

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(figsize=(8, 4))
ax.scatter(x, y)
#ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))

plt.draw()  ## 绘制以获取刻度和标签
ax.yaxis.set_ticks(ax.get_yticks())  ## 添加以确保没有警告
ax.yaxis.set_ticklabels([item.get_text()+'0' for item in ax.get_yticklabels()]) ## 获取标签,添加0并写回
plt.show()

如何在使用特定语言环境的小数分隔符时格式化小数精度?


[![enter image description here][1]][1]

<details>
<summary>英文:</summary>

it looks like `FormatStrFormatter()` doesn&#39;t take the `set_locale()` into account and uses the default `.`, which overwrites the format. So, you can get the labels, add a zero the end... Updated your code below. Hope this helps...

import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

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(figsize=(8, 4))
ax.scatter(x, y)
#ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))

plt.draw() ## Draw so you can get the ticks and labels
ax.yaxis.set_ticks(ax.get_yticks()) ## Added to ensure no warning
ax.yaxis.set_ticklabels([item.get_text()+'0' for item in ax.get_yticklabels()]) ## Get label, append 0 and write back
plt.show()


[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/Hwp8w.png

</details>



huangapple
  • 本文由 发表于 2023年5月25日 04:34:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76327225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定