嗨,
我是一名实习python开发人员,我才刚发现dash和Plotly,真是太神奇了! 对于我的应用程序,我使用的数据集包含有关1955-2005年间财富500强公司收入的信息。
我的问题是,从下拉列表中选择其他公司后,该图不会自动更新,但是,如果我选择一个新公司并删除以前的公司,则该图会更新。似乎有些情况阻止图形同时显示多条线。另外,有什么方法可以添加图例以说明哪种颜色的公司?下面是我的代码:
import dash
import dash_html_components as html
import dash_core_components as dcc
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
#Read CSV and change col. names
df = pd.read_csv('fortune500-full.csv')
df.columns = ['Year', 'Rank', 'Company', 'Revenue', 'Profit']
#Get a list of unique company names
Companies = df['Company'].unique()
#Stylesheet
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
#App layout
app.layout = html.Div([
#Dropdown
html.Div([
html.Label('Dropdown'),
dcc.Dropdown(
id = 'Dropdown',
options=[{'label': i, 'value': i} for i in Companies],
value=["General Motors"],
multi = True
),]),
#Graph
dcc.Graph(
id='Graph',
figure={
'data': [
go.Scatter(
x=df.loc[df['Company'] == i, 'Year'],
y=df.loc[df['Company'] == i, 'Revenue'],
text =df.loc[df['Company'] == i, 'Company'],
mode='lines',
name=i
) for i in df.Company.unique()],
'layout': go.Layout(
xaxis={'title': 'Year'},
yaxis={'title': 'Revenue'},
margin={'l': 50, 'b': 30, 't': 10, 'r': 0},
legend={'x': 1, 'y': 1},
hovermode='closest'
)}),
html.Div(dcc.RangeSlider(
id='Slider',
min=df['Year'].min(),
max=df['Year'].max(),
value=[1955, 2005],
marks={str(year): str(year) for year in df['Year'].unique()}
), style={'width': '98%', 'padding': '0px 20px 20px 20px'}),
html.Div(id='Output_slider',
style={'textAlign': 'center', 'color': ['#7FDBFF']}
)])
@app.callback(
dash.dependencies.Output('Graph', 'figure'),
[dash.dependencies.Input('Dropdown', 'value')])
def callback_a(dropdown_value):
trace = []
for val in dropdown_value:
trace.append(
go.Scatter(
x=df.loc[df['Company'] == val, 'Year'],
y=df.loc[df['Company'] == val, 'Revenue'],
text =df.loc[df['Company'] == val, 'Company'],
mode='lines',
name=val
),)
layout = go.Layout(
xaxis={'title': 'Year'},
yaxis={'title': 'Revenue'},
margin={'l': 50, 'b': 30, 't': 10, 'r': 0},
legend={'x': 1, 'y': 1},
hovermode='closest'
)
figure = {'data': trace, 'layout': layout}
return figure
@app.callback(
dash.dependencies.Output('Output_slider', 'children'),
[dash.dependencies.Input('Slider', 'value')])
def update_output(value):
return 'Wybrane lata: "{}"'.format(value)
#App
if __name__ == '__main__':
app.run_server(debug=True)
请问大家有什么可以帮助我找到这个问题的根源吗?
亲切的问候。