【发布时间】:2020-05-10 19:49:19
【问题描述】:
使用 plotly-dash 我可以通过选择硬编码的 csv 列来绘制图形。我尝试了不同的示例,现在我还可以从上传的文件中打印/绘制 csv。但是,我想上传一个 csv 并在下拉菜单中,我希望能够选择一列并绘制它。
有了这个,我可以通过从下拉菜单中选择一列,从硬编码的 csv 中绘制线图和箱线图。
df = pd.read_csv('df_anomaly.csv')
html.Div([
html.H3([
dcc.Dropdown(
id = 'Dropdown',
options=[{'label': k, 'value': k} for k in list(df.columns.values)[1:]],
value='a',
placeholder="Name"),
]),
], className = "filter"),
html.Div([
html.Div([
html.Div([
dcc.Graph(id='Lineplot'),
], style={'width': '75%','display': 'inline-block', 'marginLeft': '15', 'marginTop': '15'}),
html.Div([
dcc.Graph(id='Boxplot')
], style={'width': '23.8%', 'display': 'inline-block', 'marginRight': '15','marginTop': '15','float':'right'})], style={
'padding': '10px 15px'
}),
], style={'padding': '5px 0px','backgroundColor': colors['grey'], 'marginTop': '8', 'marginBottom': '8'})
])
# Updating Observed Data Plot
@app.callback(
dash.dependencies.Output('Lineplot', 'figure'),
[dash.dependencies.Input('Dropdown', 'value')])
def update_graph(selector):
df_selected = init_calc(selector)
return {
'data': [go.Scatter(
y = np.array(df_selected['selected']),
mode = 'lines',
line = dict(
color = colors['red']
)
)],
'layout': go.Layout(
height=400,
title=go.layout.Title(
text='Line Plot',
font=dict(
color = colors['black'],
)
),
xaxis=dict(
title='x',
linecolor = colors['black'],
color = colors['black'],
ticks='inside',
zeroline = False,
),
yaxis=dict(
title='y',
linecolor = colors['black'],
color = colors['black'],
ticks='inside',
zeroline = False,
),
hovermode='closest',
)
}
# Updating Boxplot
@app.callback(
dash.dependencies.Output('Boxplot', 'figure'),
[dash.dependencies.Input('Dropdown', 'value')])
def update_boxplot(selector):
df_selected = init_calc(selector)
return {
'data': [go.Box(
name='',
y=df_selected['selected'],
marker = dict(
color = colors['orange']
)
)],
'layout': go.Layout(
height=400,
title=go.layout.Title(
text='Boxplot',
font=dict(
color = colors['black'],
)
),
xaxis=dict(
linecolor = colors['black'],
color = colors['black'],
zeroline = False,
),
yaxis=dict(
title='Traffic',
linecolor = colors['black'],
color = colors['black'],
zeroline = False,
ticks='inside',
),
),
}
def init_calc(selector):
df_selected = pd.DataFrame(columns=['selected'])
df_selected['selected'] = df[str(selector)]
return df_selected
#------------------------------------------------------------------------------------
# Running the App
if __name__ == '__main__':
app.run_server(debug=False)
另外,如果我添加这段代码,我可以打印上传的 csv:
html.Div([
dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '2px'
},
# Allow multiple files to be uploaded
multiple=True
),
html.Div(id='output-data-upload'),
]),
def parse_contents(contents, filename, date):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'csv' in filename:
# Assume that the user uploaded a CSV file
df = pd.read_csv(
io.StringIO(decoded.decode('utf-8')))
elif 'xls' in filename:
# Assume that the user uploaded an excel file
df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
print(e)
return html.Div([
'There was an error processing this file.'
])
return html.Div([
html.H5(filename),
# html.H6(datetime.fromtimestamp(date)),
dash_table.DataTable(
data=df[:5].to_dict('records'),
columns=[{'name': i, 'id': i} for i in df.columns]
),
html.Hr(), # horizontal line
# For debugging, display the raw contents provided by the web browser
# html.Div('Raw Content'),
# html.Pre(contents[0:200] + '...', style={
# 'whiteSpace': 'pre-wrap',
# 'wordBreak': 'break-all'
# })
])
@app.callback(Output('output-data-upload', 'children'),
[Input('upload-data', 'contents')],
[State('upload-data', 'filename'),
State('upload-data', 'last_modified')])
def update_output(list_of_contents, list_of_names, list_of_dates):
if list_of_contents is not None:
children = [
parse_contents(c, n, d) for c, n, d in
zip(list_of_contents, list_of_names, list_of_dates)]
return children
通过小小的调整,我还可以手动选择列并绘制上传的 csv 列,但我希望能够像使用硬编码的那样选择上传的 csv 列。我该怎么做?
提前致谢
【问题讨论】:
-
你有没有考虑从这个answer开始玩?
-
@rpanai 确实,我可以从上传的 csv 创建图表,但是,我无法从下拉列表中过滤 csv 的列,而只能绘制该列。
标签: python plotly plotly-dash