首页 > 解决方案 > 如何将垂直矩形添加到子图

问题描述

我想使用 add_vrect 函数在我的子图中制作覆盖一个时间段的垂直矩形,但下面的代码什么也没产生。我不知道哪个部分不正确。请帮我!

import plotly.graph_objects as go
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from plotly.subplots import make_subplots
from datetime import timedelta
import pandas as pd 


x=[ "2015-02-01", "2015-02-02",  "2015-02-03", "2015-02-04", "2015-02-05",
    "2015-02-06", "2015-02-07", "2015-02-08", "2015-02-09", "2015-02-10",
    "2015-02-11", "2015-02-12", "2015-02-13", "2015-02-14", "2015-02-15",
    "2015-02-16", "2015-02-17", "2015-02-18", "2015-02-19", "2015-02-20",
    "2015-02-21", "2015-02-22", "2015-02-23", "2015-02-24", "2015-02-25",
    "2015-02-26", "2015-02-27", "2015-02-28"]

y=[]
for i in x:
    i=pd.to_datetime(i)
    j=i+timedelta(days=14)
    y.append(j)

fig = make_subplots(rows=2, cols=1)
  
for i in range(len(x)):
    fig.add_vrect(x0=x[i], x1=y[i], fillcolor='powderblue', opacity=0.15,
                line_width=0, row=2, col=1)

fig.show()

标签: pythonplotly

解决方案


我不确定这是什么原因(如果我弄明白了会更新答案),但似乎只有在添加某种痕迹之后才能识别轴的时间戳单位,这就是为什么你可能是得到这个情节:

在此处输入图像描述

但是,如果您从数据中绘制一个随机点(带有时间戳单位)go.Scatter,并通过设置 使其不可见opacity=0,则显示垂直矩形注释。

import plotly.graph_objects as go
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from plotly.subplots import make_subplots
from datetime import timedelta
import pandas as pd 


x=[ "2015-02-01", "2015-02-02",  "2015-02-03", "2015-02-04", "2015-02-05",
    "2015-02-06", "2015-02-07", "2015-02-08", "2015-02-09", "2015-02-10",
    "2015-02-11", "2015-02-12", "2015-02-13", "2015-02-14", "2015-02-15",
    "2015-02-16", "2015-02-17", "2015-02-18", "2015-02-19", "2015-02-20",
    "2015-02-21", "2015-02-22", "2015-02-23", "2015-02-24", "2015-02-25",
    "2015-02-26", "2015-02-27", "2015-02-28"]

y=[]
for i in x:
    i=pd.to_datetime(i)
    j=i+timedelta(days=14)
    y.append(j)

fig = make_subplots(rows=2, cols=1)

fig.add_trace(go.Scatter(x=[x[0]],y=[y[0]],mode='markers',opacity=0), row=2,col=1)

for i in range(len(x)):
    fig.add_vrect(x0=x[i], x1=y[i], fillcolor='powderblue', opacity=0.15,
                line_width=0, row=2, col=1)
fig.show()

在此处输入图像描述


推荐阅读