从CSV文件中绘制股票数据,未正确显示日期?

时间:2019-05-17 03:16:56

标签: python python-3.x matplotlib

希望有人可以指出我正确的方向。

我是Matplotlib的新手。我有一个.csv的库存数据,看起来像这样...

stock data

...我想以日期作为X标签绘制开盘价。这就是我现在正在使用的:

stock_prices = pd.read_csv(cache_filename)

# Plot the open prices
stock_prices['1. open'].plot()
plt.title('Daily Time Series for the stock (from saved CSV file)')
plt.xlabel('day')
plt.ylabel('price')
plt.show()

...但是X轴标记为Day,但仅显示数字计数,而不显示日期值:

plot now

我需要添加什么以确保X轴标记有日期?或将我指向资源。非常感谢!

2 个答案:

答案 0 :(得分:1)

尝试

import matplotlib.pyplot as plt
plt.plot(stock_prices['date'],stock_prices['1. open'])
plt.title('Daily Time Series for the stock (from saved CSV file)')
plt.xlabel('day')
plt.ylabel('price')

答案 1 :(得分:1)

您缺少两个技巧。

stock_prices = pd.read_csv(cache_filename)

# Convert the date to datetime
stock_prices['date'] = pd.to_datetime(stock_prices['date'], format = '%Y-%m-%d')
# Assign this as index
stock_prices.set_index(['date'], inplace=True)
# plot the price
stock_prices['1. open'].plot()
plt.title('Daily Time Series for the stock (from saved CSV file)')
plt.xlabel('day')
plt.ylabel('price')
plt.show()