首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在plotly-dash应用程序中绘制图形

如何在plotly-dash应用程序中绘制图形
EN

Stack Overflow用户
提问于 2020-01-16 18:04:02
回答 1查看 755关注 0票数 1

我是dash的新手,我有一个可以在dash-plotly应用程序外绘制的图,但无法在dash应用程序内绘制相同的图形。以下是我的dash应用程序代码:

代码语言:javascript
复制
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
from plotly.offline import iplot
import pandas as pd
import numpy as np

# intialise data of lists.
data = {'Name':['Nick hospital', 'Nick hospital','Nick hospital', 'Krish hospital', 'Krish hospital','Krish hospital'],
        'NAR_forms_used':[2, 1,2, 2, 2,3]
       }

# Create DataFrame
df = pd.DataFrame(data)

# get counts per NAR type
df_nar=pd.DataFrame(df.groupby('Name')['NAR_forms_used'].value_counts())
df_nar=df_nar.rename({'NAR_forms_used': 'Doc count'}, axis='columns')
df_nar=df_nar.reset_index()

# Manage NAR types (who knows, there may be more types with time?)
nars = df_nar['NAR_forms_used'].unique()
nars = nars.tolist()
nars.sort(reverse=False)

# set up plotly figure
fig = go.Figure()

# add one trace per NAR type and show counts per hospital
for nar in nars:
# subset dataframe by NAR type
    df_ply=df_nar[df_nar['NAR_forms_used']==nar]

    # add trace
    fig.add_trace(go.Bar(x=df_ply['Name'], y=df_ply['NAR count'], name='NAR Type='+str(nar)))

    # make the figure a bit more presentable

fig.update_layout(title='NAR per hospital',
                yaxis=dict(title='<i>count of NAR types</i>'),
                xaxis=dict(title='<i>Hospital</i>',
                    )
            )


fig.show()

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    dcc.Graph(id='graph'
    ),
    dcc.Dropdown(
                id="Hosp_list",
                options=[{"label": i, "value": i} for i in hosp_list],
                multi=True,
                value=list(),

        )
])





if __name__ == '__main__':
    app.run_server(debug=True)

我确实喜欢在dash dcc.graph部分显示相同的条形图。正如你所看到的,dash应用程序外部的代码运行并给出了图表,但我不确定如何在dash应用程序内部实现相同的代码。请帮助我在dash应用程序中绘制此图表

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-18 00:18:28

我重新编写了您的代码,以便它可以运行,并在Dash中呈现一个图。但是,我跳过了使用下拉菜单时应更改绘图的部分。因此,您仍然需要在dropdown回调中相应地更改绘图(参见TODO)。如果用户更改下拉菜单,则会调用此函数。

我在您的代码中更改了两项内容。不是使用fig.show,而是设置图形的“figure”属性。第二件事是全局变量不应该在Dash中使用,这就是为什么我把你的图形和数据帧创建放在函数中的原因。

代码语言:javascript
复制
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
import pandas as pd


def create_df():
    # intialise data of lists.
    data = {'Name': ['Nick hospital', 'Nick hospital', 'Nick hospital', 'Krish hospital', 'Krish hospital',
                     'Krish hospital'],
            'NAR_forms_used': [2, 1, 2, 2, 2, 3]}

    # Create DataFrame
    df = pd.DataFrame(data)

    # get counts per NAR type
    df_nar = pd.DataFrame(df.groupby('Name')['NAR_forms_used'].value_counts())
    df_nar = df_nar.rename({'NAR_forms_used': 'Doc count'}, axis='columns')
    df_nar = df_nar.reset_index()

    return df_nar

def create_figure(df_nar):
    # set up plotly figure
    fig = go.Figure()
    # Manage NAR types (who knows, there may be more types with time?)
    nars = df_nar['NAR_forms_used'].unique()
    nars = nars.tolist()
    nars.sort(reverse=False)
    # add one trace per NAR type and show counts per hospital
    data = []
    for nar in nars:
        # subset dataframe by NAR type
        df_ply = df_nar[df_nar['NAR_forms_used'] == nar]

        # add trace
        fig.add_trace(go.Bar(x=df_ply['Name'], y=df_ply['Doc count'], name='NAR Type=' + str(nar)))

    # make the figure a bit more presentable
    fig.update_layout(title='NAR per hospital',
                yaxis=dict(title='<i>count of NAR types</i>'),
                xaxis=dict(title='<i>Hospital</i>'))

    return fig

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    dcc.Graph(id='graph', figure=create_figure(create_df())),
    dcc.Dropdown(
                id="Hosp_list",
                options=[{"label": i, "value": i} for i in create_df()['Name'].tolist()],
                multi=True,
                value=list(),

        )
])

@app.callback(
    Output('graph', 'figure'),
    [Input('Hosp_list', 'value') ])
def dropdown_changed(values):
    # TODO:
    # build a graph depending on the dropdown selection (parameter values) and
    # return it instead of dash.no_update (which prevents update of client)
    print('Dropdown triggered with these values:', values)
    return dash.no_update


if __name__ == '__main__':
    app.run_server(debug=True)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59767114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档