【问题标题】:Error in displaying multiple line plots on dash-plotly在 dash-plotly 上显示多条线图时出错
【发布时间】:2020-10-20 18:07:04
【问题描述】:

我有一个代码,我尝试使用 plotly 绘制多线图。该图试图绘制十年来每个城镇的人口。

这是我的实现:

import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
import dash_html_components as html
import dash_core_components as dcc
import dash
import os
root = os.getcwd()

df = pd.read_excel(os.path.join(root, 'data', 'DCHB_Town_Release_3500.xlsx'))
# df.fillna(0, inplace=True)
df_growth = df.set_index('Town Name')
census = [column for column in df.columns if "Town Population" in column]

app = dash.Dash()
app.title = 'Town Amenities'

male_population = go.Bar(
    x=df['Town Name'],
    y=df['Total Male Population of Town'],
    name='Male'
)
female_population = go.Bar(
    x=df['Town Name'],
    y=df['Total Female Population of Town'],
    name='Female'
)

census_years = [int(a.split('Census')[1].split(')')[0].strip()) for a in census]


app.layout = html.Div(
    html.Div([
        html.H1(children='Town Amenities'),
        html.Div(children='Dashboard'),

        dcc.Graph(
            id='Total Population and Household',
            figure={
                'data': [
                    {'x': df['Town Name'], 'y': df['Total   Households '],
                        'type': 'bar', 'name':'Total Households'},
                    {'x': df['Town Name'], 'y': df['Total Population of Town'],
                     'type':'bar', 'name':'Total Population'}
                ],
                'layout': {
                    'title': 'Population and Household'
                }
            }
        ),

        dcc.Graph(
            id='Population Distribution',
            figure=go.Figure(data=[male_population, female_population],
                             layout=go.Layout(barmode='stack'))


        ),

        dcc.Graph(
            id='Areas',
            figure=go.Figure(data=[go.Pie(labels=df['Town Name'],
                                          values=df['Area (sq. km.)'],
                                          pull=[0, 0, 0.2, 0])])
        ),

        dcc.Graph(
            figure=go.Figure()
            for col in list(df['Town Name']):
                x=census
                y_temp=df_growth.loc[col]
                y=[y_temp[col] for col in census]
                figure.add_trace(
                go.Scatter(x=x, y=y,
                           name=col,
                           mode='markers+lines',
                           line=dict(shape='linear'),
                           connectgaps=True
                           )
            )

        )
    ])
)

我在此行中收到错误:for col in list(df['Town Name']): as invalid syntax(行在最后一个 dcc.Graph 部分中)。我不知道为什么,因为我在 jupyter notebook 中单独尝试过,但效果很好。也许问题是我在dcc.Graph中使用它

这段代码完美运行:

fig = go.Figure()
for col in df['Town Name']:
    x = census
    y_temp = df_growth.loc[col]
    y = [y_temp[col] for col in census]
    fig.add_trace(go.Scatter(x=x, y=y,
                             name = col,
                             mode = 'markers+lines',
                             line=dict(shape='linear'),
                             connectgaps=True
                             )
                 )
fig.show()

Desired output

【问题讨论】:

    标签: python python-3.x plotly dashboard plotly-dash


    【解决方案1】:

    我用以下代码替换了dcc.Graph 块:

    machines = [town for town in df['Town Name'] for i in range(len(census))]
    units = [df_growth.loc[town][col] for town in df['Town Name'] for col in census]
    time = census*len(df['Town Name'])
    
    dcc.Graph(
                figure=px.line(dict(machines=machines, units=units, time=time),
                               x='time', y='units', color='machines')
                # figure.update_traces(mode='markers+lines')
                # fig.show()
            )
    

    它奏效了。我不确定如何更正该代码,但像 update_trace 和 show 这样的函数只能在 jupyter notebook 上使用。

    【讨论】:

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