在Python中重新格式化多行打印中的y轴值

2024-10-02 10:24:20 发布

您现在位置:Python中文网/ 问答频道 /正文

更新了更多信息

我在这里看到了单线图的答案,但我需要一个显示两个变量的图的帮助,如果这有什么关系的话。。。总的来说,我对python是相当陌生的。我的折线图显示了过去几年两个不同部门的资金。我只想重新格式化y轴,以显示为数亿的数字

在明尼阿波利斯的一般公共资金报告中使用csv

msp_df = pd.read_csv('Minneapolis_Data_Snapshot_v2.csv',error_bad_lines=False)
msp_df.info()

将我感兴趣的两个部门保存到一个数据帧中

CPED_df = (msp_df['Unnamed: 0'] == 'CPED')
msp_df.iloc[CPED_df.values]

police_df = (msp_df['Unnamed: 0'] == 'Police')
msp_df.iloc[police_df.values]

(“test”是包含所有信息的数据框的新名称,如下所示。)

 test = pd.DataFrame({'Year': range(2014,2021), 
                      'CPED': msp_df.iloc[CPED_df.values].T.reset_index(drop=True).drop(0,0)[5].tolist(), 
                      'Police': msp_df.iloc[police_df.values].T.reset_index(drop=True).drop(0,0)[4].tolist()})

由于逗号的存在,原始数据集中的数字被读取为字符串,因此必须先修复。)

test['Police2'] = test['Police'].str.replace(',','').astype(int)
test['CPED2'] = test['CPED'].str.replace(',','').astype(int)

这是我的代码。它执行时,我只想重新格式化y轴数字比例。现在它只显示为十进制。(我已经进口了熊猫、海产熊猫和马普洛布利布)

plt.plot(test.Year, test.Police2, test.Year, test.CPED2)
plt.ylabel('Budget in Hundreds of Millions')
plt.xlabel('Year')

Current plot

非常感谢任何帮助!谢谢:)


Tags: csvtest信息dfplt数字yeardrop
1条回答
网友
1楼 · 发布于 2024-10-02 10:24:20

重新设置y轴格式的最简单方法是强制y轴采用某些值​​是用

 plt.yticks(ticks, labels)

例如,如果希望仅显示值​​从0到1,您可以执行以下操作:

plt.yticks([0,0.2,0.5,0.7,1], ['a', 'b', 'c', 'd', 'e'])

相关问题 更多 >

    热门问题