【发布时间】:2021-04-29 14:42:52
【问题描述】:
我有一个看起来像这样的数据框:
Open time Open High Low Close 4_EMA 20_EMA Position
0 2021-03-30 12:00:00 1848.86 1849.04 1826.05 1830.61 1830.610000 1830.610000 NaN
1 2021-03-30 16:00:00 1830.61 1858.29 1827.78 1858.27 1841.674000 1833.244286 1.0
2 2021-03-30 20:00:00 1858.27 1859.13 1833.50 1840.46 1841.188400 1833.931497 0.0
3 2021-03-31 00:00:00 1840.41 1862.55 1810.99 1823.17 1833.981040 1832.906592 0.0
4 2021-03-31 04:00:00 1823.18 1855.55 1801.00 1813.89 1825.944624 1831.095488 -1.0
...
我的情节代码是:
import pandas as pd
import matplotlib.pyplot as plt
df4 = pd.read_csv('data/df_4h.csv', parse_dates=['Open time'])
#df4.set_index('Open time', inplace=True) # this line causes the problem
fig, (ax2) = plt.subplots(1, 1, figsize=(15, 10))
df4['Close'].plot(ax=ax2, color = 'k', lw = 1, label = 'Close Price')
df4['4_EMA'].plot(ax=ax2, color = 'b', lw = 1, label = '4_EMA')
df4['20_EMA'].plot(ax=ax2, color = 'g', lw = 1, label = '20_EMA')
# plot 'buy' signals
ax2.plot(df4[df4['Position'] == 1].index,
df4['4_EMA'][df4['Position'] == 1],
'^', markersize = 15, color = 'g', alpha = 0.7, label = 'buy')
# plot 'sell' signals
ax2.plot(df4[df4['Position'] == -1].index,
df4['4_EMA'][df4['Position'] == -1],
'v', markersize = 15, color = 'r', alpha = 0.7, label = 'sell')
plt.show()
这样效果很好:
问题是当我尝试将 set_index 作为 Open time 列时,箭头不再显示,我不明白为什么,我需要在 x 轴刻度上插入此列,所以如果我:
...
df4.set_index('Open time', inplace=True)
...
生成的情节没有箭头(买卖,df4['4_EMA'][df4['Position'] == 1] 或 df4['4_EMA'][df4['Position'] == -1]):
如何保留箭头并在 x 轴上显示日期时间?
【问题讨论】:
标签: python python-3.x pandas matplotlib