gpt4 book ai didi

python - Matplotlib 不会在图表上绘制线条

转载 作者:行者123 更新时间:2023-12-04 04:09:47 25 4
gpt4 key购买 nike

我需要绘制这个名为 vars 的数据框:

    data       var_brl  var_ars var_bob var_clp var_cop var_mxn var_pen var_pyg var_uyu
0 01/01/2020 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
1 02/01/2020 0.17 -0.10 0.14 -0.36 -1.01 -0.49 -0.41 0.41 0.16
2 03/01/2020 1.19 -0.22 0.07 1.65 -1.01 -0.04 0.11 0.49 -0.38
3 04/01/2020 1.19 -0.22 0.07 1.65 -1.01 -0.04 0.11 0.49 -0.38
4 05/01/2020 1.19 -0.22 0.07 1.65 -1.01 -0.04 0.11 0.49 -0.38
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
135 15/05/2020 45.71 13.03 -0.07 10.07 18.98 26.43 3.78 1.81 18.19
136 16/05/2020 45.71 13.03 -0.07 10.07 18.98 26.43 3.78 1.81 18.19
137 17/05/2020 45.71 13.03 -0.07 10.07 18.98 26.43 3.78 1.81 18.19
138 18/05/2020 42.32 13.28 0.00 8.92 17.20 25.49 3.47 2.09 18.06
139 19/05/2020 43.20 13.43 0.00 8.88 16.69 25.08 3.46 2.10 18.06

我需要的是一个包含多个折线图的图表,每列一个(日期列除外,它是 x 轴)。

这是我正在使用的代码:

labels = ['Real', 'Peso Argentino', 'Boliviano', 'Peso Chileno', 'Peso Colombiano', 'Peso Mexicano',
'Novo Sol (Peru)', 'Guarani (Paraguai)', 'Peso Uruguaio']

fig, ax = plt.subplots(figsize=(16, 8))

months = mdates.MonthLocator()
months_fmt = mdates.DateFormatter('%m/%Y')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(months_fmt)

lim_i = dt.datetime.strptime(vars.iloc[0, 0], '%d/%m/%Y')
lim_f = dt.datetime.strptime(vars.iloc[-1, 0], '%d/%m/%Y')

ax.set_xlim(lim_i, lim_f + dt.timedelta(days=30))

xlim = ax.get_xlim()[1]

for i in range(1, vars.shape[1]):
if i == 1:
c = 'red'
else:
c = 'grey'

ax.plot(vars['data'], vars.iloc[:, i], color=c)
ax.text(x=float(xlim) - 28, y=vars.iloc[-1, i], s=f'{labels[i-1]} ({vars.iloc[-1, i]}%)', alpha=0.4)

ax.tick_params(bottom=False, top=False, right=False, left=False)
ax.set_ylabel('Oscilação acumulada %')
plt.grid(False)

for key, spine in ax.spines.items():
spine.set_visible(False)

plt.tight_layout()
plt.show()

这就是我得到的:

enter image description here

一切正常,但线条未绘制。谁能看出我做错了什么?

最佳答案

数据转换为日期时间

  • ax.plot(vars['data'], vars.iloc[:, i], color=c)
    • vars['data'] 仍然是字符串,您从未将其转换为日期时间
    • 刻度位置是日期时间,与字符串不匹配。
  • 它应该是 ax.plot(pd.to_datetime(df['data']), df.iloc[:, i], color=c),那么您的绘图将起作用。

enter image description here

关于python - Matplotlib 不会在图表上绘制线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61942471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com