我是python和破折号的新手。我来自C ++背景。 我正在关注教程3“ Basic Dash Callbacks”。我想在“ gapminderDataFiveYear.csv”上进行分散或(Scatter3d)多个“下拉”和“单选”项目。但是我尝试了很多次,但是数据没有显示在散点图中。请帮助解决以下代码中的错误:
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
import numpy as np
import webbrowser as wb
from os import listdir
from os.path import isfile, join
import numpy as np
#
df = pd.read_csv(
'https://raw.githubusercontent.com/plotly/'
'datasets/master/gapminderDataFiveYear.csv')
df.to_csv('test.csv')
df = pd.read_csv('./test.csv')
df['test'] = np.random.randint (10, 100, size = len(df))
col_to_choose = df.loc[:, df.dtypes == np.float64].columns.values.tolist()
app = dash.Dash()
app.layout = html.Div([
html.Div([
html.Div([
dcc.Dropdown(
id = 'xaxis-column',
options = [{'label' : i, 'value': i} for i in col_to_choose],
value = 'pop'
),
dcc.RadioItems(
id = 'xaxis-type',
options = [{'label' : i, 'value' : i} for i in ['Linear', 'Log']],
value = 'Linear',
labelStyle = {'display':'inline-block'}
)
],
style = {'width' : '48%', 'display' : 'inline-block'}),
html.Div([
dcc.Dropdown(
id = 'yaxis-column',
options = [{'label' : i, 'value': i} for i in col_to_choose],
value = 'gdpPercap'
),
dcc.RadioItems(
id = 'yaxis-type',
options = [{'label' : i, 'value' : i} for i in ['Linear', 'Log']],
value = 'log',
labelStyle = {'display':'inline-block'}
)
],
style = {'width' : '48%', 'display' : 'inline-block'}),
]),
dcc.Graph(id = 'graph-practice'),
dcc.Slider(
id = 'year-slider',
min = df['year'].min(),
max = df['year'].max(),
value = df['year'].max(),
step = None,
marks = {str(year):str(year) for year in df ['year'].unique()}
)
])
@app.callback(
dash.dependencies.Output('graph-practice', 'figure'),
[dash.dependencies.Input('xaxis-column', 'value'),
dash.dependencies.Input('yaxis-column', 'value'),
dash.dependencies.Input('xaxis-type', 'value'),
dash.dependencies.Input('yaxis-type', 'value'),
dash.dependencies.Input('year-slider', 'value')
]
)
def update_graph(xaxis_column_name, yaxis_column_name,
xaxis_type, yaxis_type,
year_value):
dff = df[df.Year == year_value]
return {
'data' : [go.Scatter(
x = dff['xaxis_column_name'].values,
y = dff['yaxis_column_name'].values,
text = dff['country'],
mode = 'markers',
marker = {
'size' : 15,
'opacity' :0.5,
'line': {'width': 0.5, 'color': 'white'}
}
)],
'layout' : go.Layout(
xaxis = {
'title': xaxis_column_name,
'type' : 'linear' if xaxis_type == 'Linear' else 'log'
},
yaxis = {
'title': yaxis_column_name,
'type' : 'linear' if yaxis_type == 'Linear' else 'log'
},
margin = {'l' : 40, 'b': 40, 't':10, 'r':0},
hovermode = 'closest'
)
}
if __name__ == '__main__':
wb.open_new('http://127.0.0.1:8050/')
app.run_server(debug = False)
答案 0 :(得分:0)
有两个问题
第一个是:
dff = df[df.Year == year_value]
df
没有 Year
列,但有 year
列 (source data)
第二个问题是这个
x = dff['xaxis_column_name'].values
y = dff['yaxis_column_name'].values
这些列也不存在。在本例中,您尝试从回调中传递 xaxis_column_name
和 yaxis_column_name
参数,但您需要传递不带引号的变量。
完整示例:
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
import numpy as np
import webbrowser as wb
from os import listdir
from os.path import isfile, join
import numpy as np
df = pd.read_csv(
"https://raw.githubusercontent.com/plotly/"
"datasets/master/gapminderDataFiveYear.csv"
)
df.to_csv("test.csv")
df = pd.read_csv("./test.csv")
df["test"] = np.random.randint(10, 100, size=len(df))
col_to_choose = df.loc[:, df.dtypes == np.float64].columns.values.tolist()
app = dash.Dash()
app.layout = html.Div(
[
html.Div(
[
html.Div(
[
dcc.Dropdown(
id="xaxis-column",
options=[{"label": i, "value": i} for i in col_to_choose],
value="pop",
),
dcc.RadioItems(
id="xaxis-type",
options=[
{"label": i, "value": i} for i in ["Linear", "Log"]
],
value="Linear",
labelStyle={"display": "inline-block"},
),
],
style={"width": "48%", "display": "inline-block"},
),
html.Div(
[
dcc.Dropdown(
id="yaxis-column",
options=[{"label": i, "value": i} for i in col_to_choose],
value="gdpPercap",
),
dcc.RadioItems(
id="yaxis-type",
options=[
{"label": i, "value": i} for i in ["Linear", "Log"]
],
value="log",
labelStyle={"display": "inline-block"},
),
],
style={"width": "48%", "display": "inline-block"},
),
]
),
dcc.Graph(id="graph-practice"),
dcc.Slider(
id="year-slider",
min=df["year"].min(),
max=df["year"].max(),
value=df["year"].max(),
step=None,
marks={str(year): str(year) for year in df["year"].unique()},
),
]
)
@app.callback(
dash.dependencies.Output("graph-practice", "figure"),
[
dash.dependencies.Input("xaxis-column", "value"),
dash.dependencies.Input("yaxis-column", "value"),
dash.dependencies.Input("xaxis-type", "value"),
dash.dependencies.Input("yaxis-type", "value"),
dash.dependencies.Input("year-slider", "value"),
],
)
def update_graph(
xaxis_column_name, yaxis_column_name, xaxis_type, yaxis_type, year_value
):
dff = df[df.year == year_value]
return {
"data": [
go.Scatter(
x=dff[xaxis_column_name].values,
y=dff[yaxis_column_name].values,
text=dff["country"],
mode="markers",
marker={
"size": 15,
"opacity": 0.5,
"line": {"width": 0.5, "color": "white"},
},
)
],
"layout": go.Layout(
xaxis={
"title": xaxis_column_name,
"type": "linear" if xaxis_type == "Linear" else "log",
},
yaxis={
"title": yaxis_column_name,
"type": "linear" if yaxis_type == "Linear" else "log",
},
margin={"l": 40, "b": 40, "t": 10, "r": 0},
hovermode="closest",
),
}
if __name__ == "__main__":
wb.open_new("http://127.0.0.1:8050/")
app.run_server(debug=False)