python - 如何不在 Dash 中显示默认的 dcc.graph 模板?

标签 python plotly plotly-dash

我试图在应用程序运行时不显示默认的 dcc.graph。我只想在应用运行时显示我的图表

enter image description here

这是我的代码,

应用布局

dbc.Row([
    dbc.Col([
        dcc.Graph(id='datatable-upload-graph', responsive=True, style={
            'display': 'block'
        })
    ], xs=10, sm=8, md=5, lg=6, xl=5)
])

回调和方法

@app.callback(
Output('datatable-upload-graph', 'figure'),
Input('container-datatable', 'data')
)
def display_gantt(container_datatable):
    df = pd.DataFrame(container_datatable)

    df['Start Date'] = pd.to_datetime(df['Start Date'], errors='coerce')
    df['End Date'] = pd.to_datetime(df['End Date'], errors='coerce')

    fig = px.timeline(df, x_start="Start Date", x_end="End Date", y="Project Name", color="Status")
    fig.update_yaxes(autorange="reversed")

    if container_datatable is None:
        return []
    else:
        return fig

app.config['suppress_callback_exceptions'] = True
if __name__ == '__main__':
    app.run_server(debug=True, use_reloader=False)

最佳答案

本质:

请确保不要离开 figure dcc.Graph 的属性未指定,而是,例如,像这样:

dcc.Graph(id='datatable-upload-graph', figure = blank_figure())

在哪里 blank_figure()是一个不仅像默认版本一样为空的图形,而且去除了所有可见的特征。


详情:

在您的应用布局中,您设置了 dcc.Graph如:

dcc.Graph(id='datatable-upload-graph', responsive=True, style={
    'display': 'block'
})

这里缺少的是 figure 的规范。属性。没有它,您的应用程序将完全正常工作,但您最终得到那个空图形,直到您设法通过您的回调之一填充图形对象。加载时间越长,空图就会变得可见。

但您可以通过指定一个 完全空白 图形来解决此问题,例如:

dcc.Graph(id='datatable-upload-graph', figure = blank_figure())

在哪里 blank_figure()这是:

def blank_fig():
    fig = go.Figure(go.Scatter(x=[], y = []))
    fig.update_layout(template = None)
    fig.update_xaxes(showgrid = False, showticklabels = False, zeroline=False)
    fig.update_yaxes(showgrid = False, showticklabels = False, zeroline=False)
    
    return fig

下面的代码片段可让您使用随机数据样本对此进行测试。该应用程序本身也非常整洁(谦虚)。没什么太花哨的,但它可以让您通过 fig.update_layout(template = <template>) 查看一些可用于您的人物的模板

不包括figure = blank_figure()dcc.Graph ,该应用将在短时间内如下所示:

enter image description here

figure = blank_figure() 应用将如下所示:

enter image description here

当模拟结束时,应用程序将如下所示:

enter image description here

现在您可以使用不同的模板轻松查看该图的外观,例如 'plotly_dark' :

enter image description here

只需在注释掉这两行之间切换,即可查看下面完整代码段中的效果。

dcc.Graph(id="graph", figure = blank_fig())
# dcc.Graph(id="graph")

完整代码:

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

import dash
import dash_core_components as dcc
import dash_html_components as html
from jupyter_dash import JupyterDash
from dash.dependencies import Input, Output


templates = ['plotly', 'seaborn', 'simple_white', 'ggplot2',
             'plotly_white', 'plotly_dark', 'presentation', 'xgridoff',
             'ygridoff', 'gridon', 'none']

def blank_fig():
    fig = go.Figure(go.Scatter(x=[], y = []))
    fig.update_layout(template = None)
    fig.update_xaxes(showgrid = False, showticklabels = False, zeroline=False)
    fig.update_yaxes(showgrid = False, showticklabels = False, zeroline=False)
    
    return fig

# startfig = blank_fig()

# Dash
app = JupyterDash(__name__)
app.layout = html.Div([
                        dcc.RadioItems(
                            id='template_radio',
                            options=[{'label': k, 'value': k} for k in templates],
                            value=templates[0]
                        ),

                        html.Hr(),
                        html.Div(id='display_templates'),
                        dcc.Graph(id="graph", figure = blank_fig())
#                         dcc.Graph(id="graph")

])

# Make a figure with selected template
@app.callback(Output('graph', 'figure'),
             [Input('template_radio', 'value')])
def make_graph(template):
    np.random.seed(1)
    start = 2021
    ncols = 50
    nrows = 100
    cols = [str(i) for i in np.arange(start, start+ncols)]
    df = pd.DataFrame(np.random.randint(-2,3, (nrows,ncols)), columns = cols).cumsum()
    df.iloc[0] = 0

    # figure
    fig = px.line(df, x=df.index, y=cols)
    fig.update_layout(template = template)

    return fig

app.run_server(mode='inline', port = 8070, dev_tools_ui=True,
          dev_tools_hot_reload =True, threaded=True)

关于python - 如何不在 Dash 中显示默认的 dcc.graph 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66637861/

相关文章:

python - Boto 找出何时使用 Restore() 将对象从 Glacier 恢复到 S3

python - 使用 matplotlib 和 python 以非常低的分辨率存储图像的解决方法

Plotly:渲染 3D 网格椭球体时的视觉伪像

python-3.x - plotly python - 修复特定图例标签的颜色

python - 在 plotly 3D 轴和刻度标签中使用 LaTeX

python - 如何将破折号托管网页变成单个静态 html 页面?

python - 为什么我用 matplotlib.imshow 绘制的 matplotlib 2D 直方图/热图与我的轴不匹配?

python - 函数 fastNlMeansDenoisingColored 中的 Opencv-python : Type of input image should be CV_8UC3 or CV_8UC4!

python-3.x - Plotly Dash 应用程序中的重定向

python - 阴谋冲刺 : How to add footnotes and source text to plots