【问题标题】:Add vrect with text to plotly express with button添加带有文本的 vrect 以使用按钮进行 plotly 表达
【发布时间】:2023-02-09 13:19:10
【问题描述】:

我在 plotly express 中有以下垂直矩形代码:

fig.add_vrect(
    x0 = '2020-04',
    x1 = '2020-09',
    fillcolor="red",
    opacity=0.25
)

我想制作一个按钮,用户可以在其中打开和关闭矩形,当它打开时,中间会有一些文本。我希望它们默认关闭。

【问题讨论】:

  • 按钮应该隐藏和显示矩形,对吗?默认情况下,矩形中间有一个文本?
  • 你想让按钮控制矩形和文本还是只控制文本?

标签: python button plotly visualization plotly-python


【解决方案1】:

您可以使用字典来创建矩形形状和矩形注释,然后将它们用作 button 的参数。一些细节:我们对按钮使用 "relayout" 方法,因为切换形状和文本注释意味着我们只更改布局,并且 argsargs2 告诉按钮在打开/关闭时如何表现。

import plotly.express as px

fig = px.scatter(
    x=['2020-01-30', '2020-04-01', '2020-04-01','2020-09-01'],
    y=[3,2,3,2]
)

rectangle_shape = [dict(
    type='rect',
    x0='2020-04',
    x1='2020-09',
    xref='x',
    y0=0,
    y1=1,
    yref='y domain',
    fillcolor='red',
    opacity=0.25
)]

rectangle_annotation = [dict(
    showarrow=False,
    x='2020-06-15',
    y=2.5,
    text="Selected Time Period"
)]

fig.update_layout(
    updatemenus=[
        dict(
            type="buttons",
            buttons=[
                dict(label="Toggle Rectangle",
                     method="relayout",
                     args=[{
                        "shapes": rectangle_shape, 
                        "annotations": rectangle_annotation}],
                     args2=[{
                        "shapes": [], 
                        "annotations": []}]),
            ],
        )
    ]
)

fig.show()

【讨论】:

    猜你喜欢
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多