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

如何将Matplotlib图表Y轴格式化为万亿美元单位?

背景说明

以下Python程序实现了以下功能:

  • 调用treasury.gov的API获取数据
  • 将数据存储到Pandas DataFrame中
  • 绘制数据图表
import requests
import pandas as pd
import matplotlib.pyplot as plt

page_size = 10000

url = 'https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_to_penny'

url_params = f'?page[size]={page_size}'

response = requests.get(url + url_params)

result_json = response.json()

df = pd.DataFrame(result_json['data'])

df['record_date'] = pd.to_datetime(df['record_date'])

rows = df[df['debt_held_public_amt'] != 'null']

rows['debt_held_public_amt'] = pd.to_numeric(rows['debt_held_public_amt'])

plt.ion()

rows.plot(x='record_date', y='debt_held_public_amt', kind='line', rot=90)

运行该程序得到对应图表,其中debt_held_public_amt字段单位为美元。

技术问询

请问如何将该图表的Y轴格式化为万亿美元单位?

解决方案

有两种实用方法可以实现Y轴的万亿美元单位格式化:

方法1:转换数据单位后绘图

直接将debt_held_public_amt的数值除以1万亿(1e12)生成新字段,再绘图并指定Y轴标签:

# 转换单位为万亿美元
rows['debt_held_public_trillion'] = rows['debt_held_public_amt'] / 1e12

# 绘制图表并设置标签
plt.ion()
ax = rows.plot(x='record_date', y='debt_held_public_trillion', kind='line', rot=90)
ax.set_ylabel('万亿美元')

方法2:用Matplotlib格式化器修改刻度(保留原始数据)

借助FuncFormatter自定义Y轴刻度显示逻辑,无需修改原始数据:

import requests
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

page_size = 10000

url = 'https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_to_penny'

url_params = f'?page[size]={page_size}'

response = requests.get(url + url_params)

result_json = response.json()

df = pd.DataFrame(result_json['data'])

df['record_date'] = pd.to_datetime(df['record_date'])

rows = df[df['debt_held_public_amt'] != 'null']

rows['debt_held_public_amt'] = pd.to_numeric(rows['debt_held_public_amt'])

plt.ion()

# 绘图并获取轴对象
ax = rows.plot(x='record_date', y='debt_held_public_amt', kind='line', rot=90)

# 定义格式化函数:将美元转为万亿美元格式
def trillion_formatter(x, pos):
    return f'{x / 1e12:.2f}'

# 应用格式化器到Y轴
ax.yaxis.set_major_formatter(FuncFormatter(trillion_formatter))
# 设置Y轴标签
ax.set_ylabel('万亿美元')

方法1直观易懂,适合仅需绘图展示的场景;方法2保留原始数据完整性,方便后续基于原始数值做其他分析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 14:25:12