我想用
make_subplots
在不同时间绘制两个图。
我该怎么办?
fig = make_subplots(rows=2, cols=1,row_heights=[0.5, 0.5], shared_xaxes=True)
fig.add_trace(go.Candlestick(x=dfpl.index, open=dfpl['open'], high=dfpl['high'], low=dfpl['low'], close=dfpl['close']), row=1, col=1)
fig.add_trace(go.Candlestick(x=dfDiv.index, open=dfDiv['open'], high=dfDiv['high'], low=dfDiv['low'], close=dfDiv['close']), row=2, col=1)
我的索引不同
datetime
。图表如下:
发布的代码是一个子图,附图是一个没有匹配内容的单个图。我不知道你的数据到底是什么,但我的理解是你想根据两个数据框绘制子图并更改x轴时间序列的显示单位。您可以使用 dtick 更改显示单位。有关 x 轴时间序列的更多信息,请参阅此处。如果要更改 x 轴的范围,请使用 range。以列表格式指定开始日期和结束日期。请参阅此处了解更多信息。
import yfinance as yf
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import datetime
dfaapl = yf.download("AAPL", start="2021-01-01", end="2024-01-01")
dfgoog = yf.download("GOOG", start="2021-01-01", end="2024-01-01")
fig = make_subplots(rows=2, cols=1,
row_heights=[0.45, 0.45],
vertical_spacing=0.4,
shared_xaxes=False)
fig.add_trace(go.Candlestick(x=dfaapl.index,
open=dfaapl['Open'],
high=dfaapl['High'],
low=dfaapl['Low'],
close=dfaapl['Close'],
name='AAPL'), row=1, col=1)
fig.add_trace(go.Candlestick(x=dfgoog.index,
open=dfgoog['Open'],
high=dfgoog['High'],
low=dfgoog['Low'],
close=dfgoog['Close'],
name='GOOG'), row=2, col=1)
fig.update_layout(height=450, margin=dict(t=20,b=0,l=0,r=0))
fig.update_xaxes(dtick='M3',tickformat="%b\n%Y", row=1,col=1)
fig.update_xaxes(range=[datetime.datetime(2022, 1, 1), datetime.datetime(2023, 12, 31)],
tickformat="%m\n%Y", row=2,col=1)
fig.show()