python - 有没有更好的方法将 Jupyter IntSlider 与 Python Plotly 结合使用?

标签 python jupyter-notebook ipywidgets plotly-python

在下面的代码块中,我使用 Jupyter IntSlider 来调整 Plotly Express 散点 3d 图中可视化的点数。该示例已经适合我的用例,但我注意到 Plotly 有 built-in slider functionalities这可以提高性能。

作为 Plotly 初学者,我发现很难将 slider 示例从 Plotly 映射到我的用例。 有什么建议吗?

import numpy as np
import plotly.express as px
import pandas as pd
from ipywidgets import interact, widgets

NUM_DOTS = 100
NUM_DIMS = 3

random_data = pd.DataFrame(np.random.random((NUM_DOTS,NUM_DIMS) ), columns=['x_1','x_2','x_3'])

def update_plotly(x):
    fig = px.scatter_3d(random_data[:x], x='x_1', y='x_2', z='x_3')
    fig.show()

interact(update_plotly, x=widgets.IntSlider(min=1, max=NUM_DOTS, step=1, value=NUM_DOTS))

最佳答案

其实构建 slider 并不难,只要按照plotly所示的示例路径即可:

import plotly.graph_objects as go
import numpy as np

NUM_DOTS = 100
NUM_DIMS = 3

# Create figure
fig = go.Figure()

# Add traces, one for each slider step
for step in np.arange(1, NUM_DOTS, 1):

    #Random data
    random_data = pd.DataFrame(np.random.random((step, NUM_DIMS)), columns=['x_1','x_2','x_3'])

    fig.add_trace(
        go.Scatter3d(
            visible=False,
            line=dict(color="#00CED1", width=6),
            name="𝜈 = " + str(step),
            z=random_data['x_3'],
            x=random_data['x_1'],
            y=random_data['x_2']))

# Make 10th trace visible
fig.data[10].visible = True

# Create and add slider
steps = []
for i in range(len(fig.data)):
    step = dict(
        method="restyle",
        args=["visible", [False] * len(fig.data)],
    )
    step["args"][1][i] = True  # Toggle i'th trace to "visible"
    steps.append(step)

sliders = [dict(
    active=10,
    currentvalue={"prefix": "Frequency: "},
    pad={"t": 50},
    steps=steps
)]

fig.update_layout(
    sliders=sliders
)

fig.show()

结果:

enter image description here

或者更多点:

enter image description here

正如您所理解的,它比小部件 slider 的性能要高得多,因为使用此方法,您只需切换 3D 散点图中的跟踪可见性即可。

关于python - 有没有更好的方法将 Jupyter IntSlider 与 Python Plotly 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59490375/

相关文章:

Python:将 python subplots() 扩展到多行/多列

python - 在Python 2.7中安装pandas v.0.13(开发版)

python-3.x - 在 jupyter notebook 中打开 .csv 文件时出现 dtype 错误

python - 以编程方式运行 ipyvuetify 按钮

python - 带 Discord.py 跳线的 Discord Bot

python - 神经网络预测区间——MVE方法

pdf - IPython/Jupyter 下载为 PDF 样式

python - 星火/PySpark : An error occurred while trying to connect to the Java server (127. 0.0.1:39543)

jupyter-notebook - ipywidgets:更改小部件值后自动更新变量并运行代码

javascript - 在 Jupyter/iPython notebook 中以图形方式选择几何对象