【发布时间】: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()
【问题讨论】:
标签: python python-3.x plotly dashboard plotly-dash