我有一个问题。实际上很烦人。基本上,我是在图表上绘制一些收入和收入数据。我这样做有零问题。问题出现在图表上的日期。在x轴上,日期从2016.0、2016.5等开始。 看这里:
有人可以帮我把日期设为整数吗?
请参阅下面的代码:
import matplotlib.pyplot as p
import matplotlib
quarterly=[{'date': '2Q2019', 'revenue': 53809000000, 'earnings': 10044000000},
{'date': '3Q2019', 'revenue': 64040000000, 'earnings': 13686000000},
{'date': '4Q2019', 'revenue': 91819000000, 'earnings': 22236000000},
{'date': '1Q2020', 'revenue': 58313000000, 'earnings': 11249000000}]
annual = [{'date': 2016, 'revenue': 215639000000, 'earnings': 45687000000}, {'date': 2017, 'revenue': 229234000000, 'earnings': 48351000000},
{'date': 2018, 'revenue': 265595000000, 'earnings': 59531000000}, {'date': 2019, 'revenue': 260174000000, 'earnings': 55256000000}]
dates,revs,earns=[],[],[]
for a in annual:
dates.append(a['date'])
revs.append(a['revenue'])
earns.append(a['earnings'])
fig, ax = p.subplots()
ax.set_title('Earnings')
ax.set_xlabel('Years')
ax.set_ylabel('Amount in $')
ax.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
p.plot(dates,revs,'-o',label='revenues')
p.plot(dates,earns,'-o',label='earnings')
p.legend()
p.show()
答案 0 :(得分:1)
pandas
,这种类型的分析就可以实现int64
转换为str
import matplotlib.pyplot as plt
import pandas as pd
# create dataframe from your list of dicts
annual = pd.DataFrame(annual)
# convert date from int64 to str
annual.date = annual.date.astype('str')
# plot
plt.plot(annual.date, annual.revenue, label='revenue')
plt.plot(annual.date, annual.earnings, label='earnings')
plt.legend()
plt.show()