Matplotlib 数字分组(小数分隔符)
基本上,当使用 matplotlib 生成绘图时,y 轴上的刻度会达到数百万。如何打开数字分组(即 1000000 显示为 1,000,000)或打开小数点分隔符?
Basically, when generating plots with matplotlib, The scale on the y-axis goes into the millions. How do I turn on digit grouping (i.e. so that 1000000 displays as 1,000,000) or turn on the decimal separator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为没有内置函数可以做到这一点。 (这就是我读完你的问题后的想法;我刚刚检查过,但在文档中找不到)。
无论如何,推出自己的产品都很容易。
(下面是一个完整的示例 - 即,它将生成一个 mpl 绘图,其中一个轴具有已命名的刻度标签 - 尽管创建自定义刻度标签只需要五行代码 - 函数的三行代码(包括 import 语句)用于创建自定义标签,两行用于创建新标签并将它们放置在指定的轴上。)
I don't think there's a built-in function to do this. (That's what i thought after i read your Q; i just checked and couldn't find one in the Documentation).
In any event, it's easy to roll your own.
(Below is a complete example--ie, it will generate an mpl plot with one axis having commified tick labels--although five lines of code are all you need to create custom tick labels--three (including import statement) for the function used to create the custom labels, and two lines to create the new labels and place them on the specified axis.)
我无法使用 doug 发布的答案,因为命令
locale.setlocale(locale.LC_ALL, ' en_US')
由于区域设置不受支持,在我的 WSL 环境中引发了错误。幸运的是,从 Python 3.8 开始,您可以利用 f 字符串进行变量格式化,包括数字分组。我将
fnx
lambda 函数定义为fnx = lambda x : f'{x:,}'
并且代码按预期工作。这是完整的工作代码,已经修改。
请注意,必须安装 Python 库 matplotlib 和 numpy 才能运行此代码。
I couldn't to use the answer posted by doug because the command
locale.setlocale(locale.LC_ALL, 'en_US')
raised an error in my WSL environment due to the unsupported locale.Fortunately, starting from Python 3.8, you can utilize f-strings for variable formatting, including digit grouping. I defined the
fnx
lambda function asfnx = lambda x : f'{x:,}'
and the code worked as intended.Here is the the full working code, already modified.
Note that the Python libraries matplotlib and numpy must be installed for this code to run.