简体   繁体   English

在不使用 Plotly Express 的情况下向 Plotly 子图添加垂直矩形

[英]Adding Vertical Rectangles to Plotly Subplots Without Using Plotly Express

I'm trying to create shaded areas that correspond to different date ranges in a plotly chart that has subplots.我正在尝试在具有子图的绘图图表中创建对应于不同日期范围的阴影区域。

Ideally I'd like for each shaded rectangle to be suitably fitted to each subplot, but I'm finding this difficult.理想情况下,我希望每个阴影矩形都适合每个子图,但我发现这很难。 Here's some sample code:这是一些示例代码:

import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots

df = pd.DataFrame({'A': list(range(25)),
                   'B': list(range(25, 50)),
                   'C': list(range(50, 75))}, index=pd.date_range('20200101', periods=25))

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

for idx, col in enumerate(df.columns):
    fig.add_trace(go.Scatter(x=df.index, y=df[col]), row=idx + 1, col=1)

shape_dict = {'type':'rect', 'xref':'x', 'yref':'paper', 'x0':'2020-01-03', 'x1':'2020-01-12', 'y0':0, 'y1':1, 'fillcolor': 'LightSalmon', 'layer': 'below', 'opacity': 0.25, 'line_width': 0}

If I do fig.update_layout(shapes=[shape_dict]) , then I get this:如果我做fig.update_layout(shapes=[shape_dict]) ,那么我得到这个:

在此处输入图片说明

Not too bad, but I'd prefer to have each of these shapes fitted separately into their own subplot.还不错,但我更喜欢将这些形状中的每一个都分别安装到它们自己的子图中。

When I try doing this with add_shape , the shaded area loses its scaling:当我尝试使用add_shape执行此add_shape ,阴影区域会失去其缩放比例:

for idx, col in enumerate(df.columns):
    fig.add_trace(go.Scatter(x=df.index, y=df[col]), row=idx + 1, col=1)
    fig.add_shape(shape_dict, row=idx + 1, col=1)

And that gives me this:这给了我这个:

在此处输入图片说明

I would prefer not to have to re-calculate axes individually.我宁愿不必单独重新计算轴。

I also can't access add_vrect -- I'm not sure why, but it's not available as a method, and I also can't use plotly.express , and most of the plot.ly's documentation uses the px charts and their methods to do what I'm describing.我也无法访问add_vrect -- 我不知道为什么,但它不能作为一种方法使用,而且我也不能使用plotly.express ,而且大多数 plot.ly 的文档都使用px图表及其方法做我所描述的。

EDIT编辑

To respond to the answer below, add_vrect does not work on my version of plotly, which is 4.12.0.为了回应下面的答案, add_vrect不适用于我的 plotly 版本,即 4.12.0。

For example the sample code in r-beginners returns me this:例如, r-beginners的示例代码返回给我:

df = pd.DataFrame({'A': list(range(25)),
                   'B': list(range(25, 50)),
                   'C': list(range(50, 75))}, index=pd.date_range('20200101', periods=25))

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

for idx, col in enumerate(df.columns):
    fig.add_trace(go.Scatter(x=df.index, y=df[col]), row=idx + 1, col=1)

# shape_dict = {'type':'rect', 'xref':'x', 'yref':'paper', 'x0':'2020-01-03', 'x1':'2020-01-12', 'y0':0, 'y1':1, 'fillcolor': 'LightSalmon', 'layer': 'below', 'opacity': 0.25, 'line_width': 0}
# fig.update_layout(shapes=[shape_dict])

fig.add_vrect(
    x0="2020-01-03", x1="2020-01-12",
    y0=0, y1=1,
    fillcolor="LightSalmon", opacity=0.25,
    layer="below", line_width=0)

fig.show()

Returns the error message: AttributeError: 'Figure' object has no attribute 'add_vrect'返回错误信息: AttributeError: 'Figure' object has no attribute 'add_vrect'

Shading is output to each subplot with add_vrect() .使用add_vrect()将阴影输出到每个子图。 The scale is not affected either.规模也不受影响。 Does this answer meet your question's intent?这个答案是否符合你的问题的意图?

import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots

df = pd.DataFrame({'A': list(range(25)),
                   'B': list(range(25, 50)),
                   'C': list(range(50, 75))}, index=pd.date_range('20200101', periods=25))

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

for idx, col in enumerate(df.columns):
    fig.add_trace(go.Scatter(x=df.index, y=df[col]), row=idx + 1, col=1)

# shape_dict = {'type':'rect', 'xref':'x', 'yref':'paper', 'x0':'2020-01-03', 'x1':'2020-01-12', 'y0':0, 'y1':1, 'fillcolor': 'LightSalmon', 'layer': 'below', 'opacity': 0.25, 'line_width': 0}
# fig.update_layout(shapes=[shape_dict])

fig.add_vrect(
    x0="2020-01-03", x1="2020-01-12",
    y0=0, y1=1,
    fillcolor="LightSalmon", opacity=0.25,
    layer="below", line_width=0,
)

fig.show()

在此处输入图片说明

I can't comment, so posting this as a (potential) answer.我无法发表评论,因此将其作为(潜在)答案发布。

Are you using this within Jupyter?你在 Jupyter 中使用它吗? If so, is the jupyterlab-plotly extension for plotly also updated?如果是这样,是否也更新了jupyterlab-plotly扩展? If not, this might explain why you can't access the add_vrect method.如果没有,这可能解释了为什么您无法访问add_vrect方法。 I think the jupyterlab extensions are mostly responsible for the rendering, but it might still throw an error of not finding the method.我认为 jupyterlab 扩展主要负责渲染,但它仍然可能会抛出找不到方法的错误。 Quickest way to check/update is jupyter labextension update --all .检查/更新的最快方法是jupyter labextension update --all

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM