在Plotly Express中,我可以使用数据创建散点图.很容易:
import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", log_x=True, color='continent')
有没有办法将下拉菜单添加到绘图中,以便我也可以 Select 其他参数作为 colored颜色 ?这样做不应重置zoom .
除了使用Dash应用程序外,我想不出怎么做,但我仍然有一些问题:悬停不变,无法在分类 colored颜色 和数字 colored颜色 之间切换.让我告诉你我到目前为止所取得的成就:
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
import numpy as np
df = px.data.gapminder()
df["moreData1"] = np.random.normal(size = len(df))
labels = df.columns[df.dtypes=="float64"]
#labels = df.columns
options = [{'label': v, 'value': v} for v in labels]
app = dash.Dash(__name__)
fig = px.scatter(df,
x="gdpPercap",
y="lifeExp",
log_x=True,
color=labels[1],
#color='continent',
render_mode='webgl'
)
# somehow this line prevents from resetting the zoom. Do not really understand why.
fig.update_layout(uirevision='some_unique_value')
# Define the layout
app.layout = html.Div([
dcc.Dropdown(
id='color-dropdown',
options=options,
value=labels[-1]
),
dcc.Graph(
id='scatter-plot',
figure=fig
)
])
# Define the callback to update the scatter plot based on the selected color
@app.callback(
Output('scatter-plot', 'figure'),
[Input('color-dropdown', 'value')]
)
def update_scatter_plot(selected_color):
fig.update_traces(
marker_color=df[selected_color]
)
return fig
# Run the app
if __name__ == '__main__':
app.run(debug=True, port=8052)
它以某种方式工作,但我希望有两个改进:我希望也能够显示类别值(不能像您看到的那样,通过设置labels = df.columns
而不仅仅是数字列来工作.
更重要的是,我希望在悬停时显示 colored颜色 信息.
没有必要使用一个破折号应用程序,我想我会更高兴一个纯粹的情节情节.