Overlapping Dates in Candlestick Plot from a Pandas DataFrame

一世执手 提交于 2019-11-29 02:57:30

问题


I have a pandas dataframe output as follows

        Open   High    Low  Close
2016-06-01  69.60  70.20  69.44  69.76
2016-06-02  70.00  70.15  69.45  69.54
2016-06-03  69.51  70.48  68.62  68.91
2016-06-04  69.51  70.48  68.62  68.91
2016-06-05  69.51  70.48  68.62  68.91
2016-06-06  70.49  71.44  69.84  70.11

I've used the following code to make the candlestick plot:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
from matplotlib.finance import candlestick_ohlc
import matplotlib.dates as mdates
import datetime as dt

#Reset the index to remove Date column from index
df_ohlc = df.reset_index()

#Naming columns
df_ohlc.columns = ["Date","Open","High",'Low',"Close"]

#Converting dates column to float values
df_ohlc['Date'] = df_ohlc['Date'].map(mdates.date2num)

#Making plot
fig = plt.figure()
ax1 = plt.subplot2grid((6,1), (0,0), rowspan=6, colspan=1)

#Converts raw mdate numbers to dates
ax1.xaxis_date()
plt.xlabel("Date")
print(df_ohlc)

#Making candlestick plot
candlestick_ohlc(ax1,df_ohlc.values,width=1, colorup='g', colordown='k',alpha=0.75)
plt.ylabel("Price")
plt.legend()

plt.show()

I get a candlestick plot but the dates overlap, I want to know how to fix this issue? Moreover I want to know why the legend is not showing up.


回答1:


You can rotate the dates by adding:

for label in ax1.xaxis.get_ticklabels():
    label.set_rotation(45)

above your plt.show()

Pandas will also do this for you if you were to add a moving average with something like:

df_ohlc['10MA'] = pd.rolling_mean(ohlc['close'], 10)
df_ohlc['10MA'].plot(ax=ax1, label = '10MA')

As I understand, you're not seeing the legend because the candlestick chart is understood and needs no labeling. However, if you were to add the moving average, it's 'label = 10MA' would show up in a legend.

I hope this is as helpful as it is late. I came across this post while searching for other help.




回答2:


The following code resolves data overlapping issue

fig.autofmt_xdate()


来源:https://stackoverflow.com/questions/42437349/overlapping-dates-in-candlestick-plot-from-a-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!