来自 Pandas DataFrame 的烛台图中的重叠日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42437349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:03:29  来源:igfitidea点击:

Overlapping Dates in Candlestick Plot from a Pandas DataFrame

pythonpandasmatplotlibfinancecandlestick-chart

提问by

I have a pandas dataframe output as follows

我有一个Pandas数据框输出如下

        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.

我得到一个烛台图,但日期重叠,我想知道如何解决这个问题?此外,我想知道为什么传说没有出现。

Candlestick plot figure

烛台图

采纳答案by d_sa

The following code resolves data overlapping issue

以下代码解决数据重叠问题

fig.autofmt_xdate()

回答by d_sa

You can rotate the dates by adding:

您可以通过添加以下内容来旋转日期:

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

above your plt.show()

在你的 plt.show() 之上

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

如果您要添加以下内容的移动平均线,Pandas 也会为您执行此操作:

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.

据我了解,您没有看到图例,因为烛台图表已被理解并且不需要标记。但是,如果您要添加移动平均线,则“标签 = 10MA”将显示在图例中。

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

我希望这是有帮助的,因为它已经晚了。我在寻找其他帮助时遇到了这篇文章。