我想将 Plotly 与下拉小部件混合使用,目的是制作一些散点图并通过小部件修改 x 轴。假设我的数据集如下:
import sea born as sns import plotly.graph_objects as go import pandas as pd import ipywidgets as widgets import seaborn as sns df = sns.load_dataset('diamonds')
我的目标是列carat。到目前为止,我尝试的是创建散点图,将它们包含到小部件中并显示它:
carat
predictors = df.columns.tolist() predictors.remove("carat") target = df["carat"] data = [] for predictor in predictors: chart = go.Scatter(x = df[predictor], y = target, mode="markers") fig = go.Figure(data=chart) data.append((predictor,fig)) widgets.Dropdown(options = [item[0] for item in data], value = [item[0] for item in data][0], description = "Select :", disabled=False)
但是,我是 ipywidgets/plotly 的新手,不明白这里哪里出了问题,因为即使我更改了它的值,它也会显示小部件,但不显示图表。我该如何修改代码,以便它在选择预测器时最终显示图表?
你可以使用 widgets.interactive 来实现当下拉菜单选择改变时更新图表。为了显示图表,你需要在小部件的 value 更改时调用更新图表的函数。以下是修改后的代码,它可以根据选择的特征(predictor)更新散点图:
widgets.interactive
value
predictor
import seaborn as sns import plotly.graph_objects as go import ipywidgets as widgets from IPython.display import display # Load the dataset df = sns.load_dataset('diamonds') # Prepare predictors and target predictors = df.columns.tolist() predictors.remove("carat") target = df["carat"] # Function to update the plot based on selected predictor def update_plot(predictor): fig = go.Figure(data=go.Scatter(x = df[predictor], y = target, mode="markers")) fig.update_layout(title=f"Scatter plot of {predictor} vs carat", xaxis_title=predictor, yaxis_title="Carat") fig.show() # Create the dropdown widget and make it interactive dropdown = widgets.Dropdown(options=predictors, value=predictors[0], # default to the first predictor description="Select Predictor:", disabled=False) # Use interactive to link dropdown value to the plot update function widgets.interactive(update_plot, predictor=dropdown) # Display the widget and plot display(dropdown)
update_plot
fig.show()
运行这个代码后,你应该能够通过选择不同的预测变量,动态更新图表!