如何在 matplotlib 中用逗号将轴号格式格式化为千位? [英] How do I format axis number format to thousands with a comma in matplotlib?

查看:49
本文介绍了如何在 matplotlib 中用逗号将轴号格式格式化为千位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 x 轴上的数字格式更改为 10,000 而不是 10000?理想情况下,我只想做这样的事情:

x = format((10000.21, 22000.32, 10120.54), "#,###")

代码如下:

将 matplotlib.pyplot 导入为 plt# 创建图形实例fig1 = plt.figure(1)fig1.set_figheight(15)fig1.set_figwidth(20)ax = fig1.add_subplot(2,1,1)x = 10000.21、22000.32、10120.54y = 1, 4, 15ax.plot(x, y)ax2 = fig1.add_subplot(2,1,2)x2 = 10434、24444、31234y2 = 1, 4, 9ax2.plot(x2, y2)图1.show()

解决方案

Use , as 格式说明符:

<预><代码>>>>格式(10000.21,',')'10,000.21'

或者,您也可以使用 str.format 而不是 format:

<预><代码>>>>'{:,}'.format(10000.21)'10,000.21'

<小时>

使用 matplotlib.ticker.FuncFormatter:

<代码>...ax.get_xaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))ax2.get_xaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))图1.show()

How can I change the format of the numbers in the x-axis to be like 10,000 instead of 10000? Ideally, I would just like to do something like this:

x = format((10000.21, 22000.32, 10120.54), "#,###")

Here is the code:

import matplotlib.pyplot as plt

# create figure instance
fig1 = plt.figure(1)
fig1.set_figheight(15)
fig1.set_figwidth(20)

ax = fig1.add_subplot(2,1,1)

x = 10000.21, 22000.32, 10120.54

y = 1, 4, 15
ax.plot(x, y)

ax2 = fig1.add_subplot(2,1,2)

x2 = 10434, 24444, 31234
y2 = 1, 4, 9
ax2.plot(x2, y2)

fig1.show()

解决方案

Use , as format specifier:

>>> format(10000.21, ',')
'10,000.21'

Alternatively you can also use str.format instead of format:

>>> '{:,}'.format(10000.21)
'10,000.21'


With matplotlib.ticker.FuncFormatter:

...
ax.get_xaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
ax2.get_xaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
fig1.show()

这篇关于如何在 matplotlib 中用逗号将轴号格式格式化为千位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆