我正在尝试使用matplotlib开发烛台图表但由于某种原因,日期不会出现在x轴上。在stackoverflow中搜索之后,我明白日期需要转换为浮点数,所以我也转换了它们但仍然无法正常工作。这个python和matplotlib的新功能。非常感谢你的帮助。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ohlc
import matplotlib.dates as dts
import matplotlib.ticker as mTicker
from datetime import datetime
my_file=pd.read_csv("C:\\path\\to\\file\\file.csv",sep=",",names=['Date','Open','High','Low','Close','AdjClose','Volume'],skiprows=1)
dateseries=[]
for i in my_file['Date']:
dateseries.append(dts.date2num(datetime.strptime(i,'%Y-%m-%d')))
print(dateseries)
fig,ax1=plt.subplots()
candlestick2_ohlc(ax1,my_file['Open'], my_file['High'],my_file['Low'], my_file['Close'], width=0.7,colorup='#008000', colordown='#FF0000')
plt.show()
示例数据:
Date,Open,High,Low,Close,Volume1,Volume2
2017-05-08,149.029999,153.699997,149.029999,153.009995,153.009995,48752400
2017-05-09,153.869995,154.880005,153.449997,153.990005,153.990005,39130400
2017-05-10,153.630005,153.940002,152.110001,153.259995,153.259995,25805700
答案 0 :(得分:2)
一般来说,你对“日期需要转换成浮点数”是对的。然后要在x轴上显示日期,您需要将它们“转换”回来。如果您不介意使用candlestick_ohlc
,可能更容易为您的案例设置x轴:
import io
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick_ohlc
from matplotlib.dates import date2num, DayLocator, DateFormatter
import pandas as pd
s = """Date,Open,High,Low,Close,Volume1,Volume2
2017-05-08,149.029999,153.699997,149.029999,153.009995,153.009995,48752400
2017-05-09,153.869995,154.880005,153.449997,153.990005,153.990005,39130400
2017-05-10,153.630005,153.940002,152.110001,153.259995,153.259995,25805700"""
my_file = pd.read_table(io.StringIO(s), sep=',', header=0)
my_file['Date'] = date2num(pd.to_datetime(my_file['Date']).tolist())
fig, ax=plt.subplots()
candlestick_ohlc(ax, my_file.as_matrix())
ax.xaxis.set_major_locator(DayLocator())
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
plt.show()