Suraj
Suraj

Reputation: 2477

Error in displaying multiple line plots on dash-plotly

I have a code where I try to draw a multiple line plot using plotly. The graph tries to plot the population of each town over the decade.

This is my implementation :

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
                           )
            )

        )
    ])
)

I get an error in this line : for col in list(df['Town Name']): as invalid syntax (line is present in last dcc.Graph section). I don't know why as I tried it separately in jupyter notebook and it worked perfectly. Maybe the problem is that I use it within a dcc.Graph

This code worked perfectly :

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

Upvotes: 1

Views: 812

Answers (1)

Suraj
Suraj

Reputation: 2477

I replaced the dcc.Graph block with the following piece of code :

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()
        )

and it worked. I am not sure how to correct that code, but functions like update_trace and show can be used only on jupyter notebook.

Upvotes: 1

Related Questions