问题描述
我正在尝试在同一x轴(Jan01-Dec31)上绘制多个烛台(来自单个数据框)。
例如,我获得了某只特定股票的最近5年的股票数据,并且我想在同一x轴上(Jan01-Dec31)在彼此上方绘制每年的烛台。
轴看起来像:
x轴:Jan01,jan02 ... Dec31
y轴:Year1,Year2,... YearN数据作为相同X轴上彼此重叠的烛台。
多年来,我正在使用 pandas_datareader.get_data_yahoo()从Yahoo Finance提取股票数据。我添加了两个带有不同格式日期的辅助列,以尝试显示带有月和日的x轴,并且仍然在同一x轴上生成多个图。
这是我的数据框中的示例,其中添加了列date2和date3
Sample Dataframe
要进行绘图,我将DataFrame按年份进行划分,并且每年从plotly.graph_objects中获取一个Candlestick类型的对象。
我陷入了两个不可取的选择之间:
1-使用 df ['date3'] = df1.index.strftime(“%b%d”)作为x轴(与Jan01一样转换为月份和日期)。
问题是,如果我尝试将日期转换为月份和日期(不包括年份),则结果图会将所有日期附加到x轴上。 x轴(而不是序列Jan01-Dec31)将附加所有日期,例如Jan01-Dec31Jan01-Dec31Jan01-Dec31。
Wrong graph with labels as month and day
2-使用 df ['date2'] = df1.index.strftime(“%j”)作为x轴(转换为类似于1-365的年份)。 使用x轴作为1-365中的数字,我可以完全按照需要绘制图形,但是x轴不显示Month and Day,因为它显示1-365 Right graph but wrong x axis labels(1-365 instead of Jan01-Dec31)
3-通过在Stackoverflow(Python - Plot Multiple Dataframes by Month and Day (Ignore Year))上有一个不同上下文的相似主题,我找到了一个关于散乱文档(https://plotly.com/python/tick-formatting/#tickmode--array)的可能解决方案,但这对我不起作用。想法是更新报价值和类似这样的文本:
fig.update_layout(
xaxis = dict(
tickmode = 'array',tickvals = [1,3,5,7,9,11],ticktext = ['One','Three','Five','Seven','Nine','Eleven']
)
)
plotObj = go.Candlestick(
x=dfResult[start_index:end_index]['date2'],xaxis=dict(
tickmode='array',tickvals=dfResult[start_index:end_index]['date2'],ticktext=dfResult[start_index:end_index]['date3']
),open=dfResult[start_index:end_index]['Open'],high=dfResult[start_index:end_index]['High'],low=dfResult[start_index:end_index]['Low'],close=dfResult[start_index:end_index]['Close'],name="%s" % trace_label
)
这是我尝试运行以上代码时遇到的错误(添加xaxis = dict()):
ValueError:
Invalid value of type 'builtins.dict' received for the 'xaxis' property of candlestick
Received value: {'tickmode': 'array','tickvals': 0 308
1 309
2 310
3 313
4 314
5 315
6 316
7 317
8 320
9 321
10 322
11 323
12 324
13 327
14 328
15 329
16 331
17 334
18 335
19 336
20 337
21 338
22 341
23 342
24 343
25 344
26 345
27 348
28 349
29 350
30 351
31 352
32 355
33 356
34 357
35 358
36 362
37 363
38 364
39 365
Name: date2,dtype: int64,'ticktext': 0 Nov 04
1 Nov 05
2 Nov 06
3 Nov 09
4 Nov 10
5 Nov 11
6 Nov 12
7 Nov 13
8 Nov 16
9 Nov 17
10 Nov 18
11 Nov 19
12 Nov 20
13 Nov 23
14 Nov 24
15 Nov 25
16 Nov 27
17 Nov 30
18 Dec 01
19 Dec 02
20 Dec 03
21 Dec 04
22 Dec 07
23 Dec 08
24 Dec 09
25 Dec 10
26 Dec 11
27 Dec 14
28 Dec 15
29 Dec 16
30 Dec 17
31 Dec 18
32 Dec 21
33 Dec 22
34 Dec 23
35 Dec 24
36 Dec 28
37 Dec 29
38 Dec 30
39 Dec 31
Name: date3,dtype: object}
The 'xaxis' property is an identifier of a particular
subplot,of type 'x',that may be specified as the string 'x'
optionally followed by an integer >= 1
(e.g. 'x','x1','x2','x3',etc.)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)