如何使用逗号将轴数字格式格式化为千位

2025-03-19 08:57:00
admin
原创
73
摘要:问题描述:如何将 x 轴上的数字格式改为 而不是10,000?10000理想情况下,我只想做这样的事情:x = format((10000.21, 22000.32, 10120.54), "#,###") 以下是代码:import matplotlib.pyplot as plt # ...

问题描述:

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

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

以下是代码:

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()

解决方案 1:

用作,格式说明符:

>>> format(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), ',')))
fig1.show()

在此处输入图片描述

解决方案 2:

我发现最好的方法是StrMethodFormatter

import matplotlib as mpl
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))

例如:

import pandas as pd
import requests
import matplotlib.pyplot as plt
import matplotlib as mpl

url = 'https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USDT&aggregate=1'
df = pd.DataFrame({'BTC/USD': [d['close'] for d in requests.get(url).json()['Data']]})

ax = df.plot()
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
plt.show()

在此处输入图片描述

解决方案 3:

每次我尝试这样做时,我总是发现自己处于同样的境地。当然,其他答案也能完成工作,但下次不容易记住!例如:导入 ticker 并使用 lambda、自定义 def 等。

如果您有一个名为的轴,那么这是一个简单的解决方案ax

ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])

解决方案 4:

简短回答,无需导入matplotlib as mpl

plt.gca().yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter('{x:,.0f}'))

修改自@AlexG 的回答

解决方案 5:

如果你喜欢简短的,你也可以更新标签

def update_xlabels(ax):
    xlabels = [format(label, ',.0f') for label in ax.get_xticks()]
    ax.set_xticklabels(xlabels)

update_xlabels(ax)
update_xlabels(ax2)

解决方案 6:

您可以使用matplotlib.ticker.funcformatter

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr


def func(x, pos):  # formatter function takes tick label and tick position
    s = '%d' % x
    groups = []
    while s and s[-1].isdigit():
        groups.append(s[-3:])
        s = s[:-3]
    return s + ','.join(reversed(groups))

y_format = tkr.FuncFormatter(func)  # make formatter

x = np.linspace(0,10,501)
y = 1000000*np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)
ax.yaxis.set_major_formatter(y_format)  # set formatter to needed axis

plt.show()

在此处输入图片描述

解决方案 7:

x = [10000.21, 22000.32, 10120.54]

您可以使用列表推导来创建标签列表,然后将它们传递给plt.xticks

xlabels = [f'{label:,}' for label in x]
plt.xticks(x, xlabels)

解决方案 8:

我认为最简单的方法:

current_values = plt.gca().get_yticks()
plt.gca().set_yticklabels(['{:,.0f}'.format(x) for x in current_values])

来自:
https ://queirozf.com/entries/matplotlib-examples-number-formatting-for-axes-labels

解决方案 9:

如果您希望原始值以刻度显示,请使用

plt.xticks(ticks=plt.xticks()[0], labels=plt.xticks()[0])

这将防止出现从 3000000 到 1.3 e5 等缩写,并将以刻度显示 3000000(精确值)。

解决方案 10:

对于非逗号分隔符,改进接受的答案,下面的答案将用作SEP分隔符。

SEP = '.'

ax.get_yaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(
        lambda x, p: str.replace(format(int(x), ','), ',', SEP)
    )
)
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   3938  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   2732  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Freshdesk、ClickUp、nTask、Hubstaff、Plutio、Productive、Targa、Bonsai、Wrike。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在项目管理过程中面临着诸多痛点,如任务分配不...
项目管理系统   72  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Monday、TeamGantt、Filestage、Chanty、Visor、Smartsheet、Productive、Quire、Planview。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多项目经理和团队在管理复杂项目时,常...
开源项目管理工具   79  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Smartsheet、GanttPRO、Backlog、Visor、ResourceGuru、Productive、Xebrio、Hive、Quire。在当今快节奏的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在选择项目管理工具时常常面临困惑:...
项目管理系统   66  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用