【问题标题】:Plotly Dash: Display a variable inside Markdown textPlotly Dash:在 Markdown 文本中显示变量
【发布时间】:2020-05-26 21:13:47
【问题描述】:

我是 Dash 和 Plotly 生态系统的新手,几天前开始构建基于 Web 的仪表板。

这是一段sn-p代码:

import dash
import dash_html_components as html
import dash_core_components as dcc


# initialize the application
app = dash.Dash()

# define the layout of the app
app.layout = html.Div([

# add a date range selector
dcc.DatePickerRange(
    id = 'my-date-picker-range',
    min_date_allowed = dt(2010,1,4),
    max_date_allowed = dt(2020, 12, 31),
    initial_visible_month = dt(2020, 5, 23)
),

html.Div(id = 'output-container-date-picker-range'),

# add some markdown text
dcc.Markdown(f'''
    This report covers the time period spanning {start_date} to {end_date}.
    '''),

])


@app.callback(
    dash.dependencies.Output('output-container-date-picker-range', 'children'),
    [dash.dependencies.Input('my-date-picker-range', 'start_date'),
     dash.dependencies.Input('my-date-picker-range', 'end_date')])

app.run_server(debug = True)

我正在尝试在降价文本中显示start_dateend_date 变量(使用f string)。不幸的是,我收到以下错误消息:

NameError: name 'start_date' is not defined

是否可以在 Markdown 文本中包含变量输出?谢谢!

【问题讨论】:

  • 也许你正在寻找这个: dcc.Markdown("#### 格式化文本," + variable_to_show + "!格式化继续:" + another_variable + ".") 而不是 f-string和三引号,您可以像字符串一样使用 + 号连接降价文本。

标签: python plotly markdown plotly-dash


【解决方案1】:

您正在使用装饰器 (@app.callback),但您没有将其附加到要执行的函数。您需要将装饰器附加到负责更新正确 div 的函数。

我认为你最好的选择是坚持documentation

这给出了与您想要的类似的结果:

import dash
import dash_html_components as html
import dash_core_components as dcc
from datetime import datetime as dt

# initialize the application
app = dash.Dash()

# define the layout of the app
app.layout = html.Div([

    # add a date range selector
    dcc.DatePickerRange(
        id = 'my-date-picker-range',
        min_date_allowed = dt(2010,1,4),
        max_date_allowed = dt(2020, 12, 31),
        initial_visible_month = dt(2020, 5, 23)
    ),

    html.Div(id = 'output-container-date-picker-range'),
])

@app.callback(
    dash.dependencies.Output('output-container-date-picker-range', 'children'),
    [dash.dependencies.Input('my-date-picker-range', 'start_date'),
     dash.dependencies.Input('my-date-picker-range', 'end_date')])
def update_output_div(start_date, end_date):
    return f"This report covers the time period spanning {start_date} to {end_date}"

app.run_server(debug = True)

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2019-06-25
    • 2022-07-30
    • 2022-01-06
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多