简体   繁体   English

如何在Matplotlib X轴中显示日期而不是序列号

[英]How to display dates in matplotlib x-axis instead of sequence numbers

I am trying to develop a candlestick chart with matplotlib but for some reason, dates are not coming up in the x-axis. 我正在尝试使用matplotlib开发烛台图,但是由于某些原因,x轴上的日期没有显示出来。 After searching in stackoverflow, I understood that the dates need to be converted to float numbers so i converted them as well but still it's not working. 在stackoverflow中搜索之后,我了解到日期需要转换为浮点数,因此我也将它们转换了,但仍然无法正常工作。 New to this python and matplotlib. 这个python和matplotlib的新手。 ANy help would be greatly appreciated. 任何帮助将不胜感激。

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()

Sample data: 样本数据:

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

In general, you are right about "the dates need to be converted to float numbers". 通常,您对“日期必须转换为浮点数”是正确的。 Then to display dates on x-axis, you would need to "convert" them back. 然后,要在x轴上显示日期,您需要将其“转换”回去。 If you don't mind using candlestick_ohlc , that might be easier for setting the x-axis for your case here: 如果您不介意使用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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM