pandas 将y轴格式设置为万亿美元

ccgok5k5  于 2023-11-15  发布在  其他
关注(0)|答案(2)|浏览(80)

下面是一个Python程序,它执行以下操作:

  • 对treasury.gov进行API调用以检索数据
  • 将数据存储在Pandas框架中
  • 绘制数据
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轴格式化为数万亿美元的好方法是什么?

vngu2lb8

vngu2lb81#

下面是一个使用FuncFormatter的方法。
这种方法避免了为万亿值使用额外的列。

import requests
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
# ----------------------------------------------------------------------
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'])

# ----------------------------------------------------------------------
plt.ion()
# ----------------------------------------------------------------------

df['debt_held_public_amt'] = pd.to_numeric(df['debt_held_public_amt'], errors='coerce')

plt.ion()

ax = df.plot(x='record_date', y=['debt_held_public_amt', 'intragov_hold_amt', 'tot_pub_debt_out_amt'], kind='line', rot=90)

ax.yaxis.set_major_formatter(mtick.FuncFormatter(lambda x, pos: '$' + '{:1.0f}'.format(x/1000/1000/1000/1000) + 'T'))

字符串


的数据

fslejnso

fslejnso2#

我环顾四周,想找一个看起来不错的人,我在维基百科上找到了this graph
我决定这么做。
首先,我将金额转换为一个数字。我发现您执行此转换的代码对我不起作用-它创建了一个SettingWithCopy警告。

rows = df[df['debt_held_public_amt'] != 'null'].copy()
rows['debt_held_public_amt'] = pd.to_numeric(rows['debt_held_public_amt'])

字符串
接下来,我做了一个单位转换,并设置刻度格式,在每个数字周围放上'$ T'。

rows['debt_held_public_amt_tr'] = rows['debt_held_public_amt'] / 1e12
ax = rows.plot(x='record_date', y='debt_held_public_amt_tr', kind='line', rot=90)
ax.yaxis.set_major_formatter('${x:.0f} T')


参见matplotlib文档中的Dollar ticks

相关问题