使用 Plotly 的 Slider 交互式绘图 [英] Interactive plot with Slider using Plotly

查看:29
本文介绍了使用 Plotly 的 Slider 交互式绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Plotly 在 Python 中重新创建以下交互式绘图?

How do I recreate the following interactive plot in Python using Plotly?

我的简单示例绘制了一个条形图,其中一列 x 和另一列 1-x.

My simple example draws a bar chart with one column x and another 1-x.

来自 Mathematica 的 GIF:

GIF from Mathematica:

滑块允许在 0 和 1 之间变化 x.

Slider allows for a varying x between 0 and 1.

数学代码:

Manipulate[BarChart[{x, 1 - x}, PlotRange -> {0, 1}], 
    {{x, 0.3, "Level"}, 0, 1, Appearance -> "Open"}]

<小时>

更新

这是一个我不喜欢的解决方案:

Here is a solution which I don't like:

import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)

import ipywidgets as widgets

绘图:

def update_plot(x):
    data = [go.Bar(
                x=['1', '2'],
                y=[x, 1-x]
    )]
    iplot(data, show_link=False)

x = widgets.FloatSlider(min=0, max=1, value=0.3)
widgets.interactive(update_plot, x=x)

这个问题:

  • 当滑块移动时,情节会闪烁
  • 滑块放错位置
  • 增量不够细化
  • 我自己无法指定准确的值

推荐答案

从 Plotly 3.0 开始,可以按如下方式实现(在 JupyterLab 中):

Starting from Plotly 3.0 this can be achieved as follows (in JupyterLab):

import plotly.graph_objects as go
from ipywidgets import interact

fig = go.FigureWidget()
bar = fig.add_bar(x=['x', '1-x'])
fig.layout = dict(yaxis=dict(range=[0,1]), height=600)

@interact(x=(0, 1, 0.01))
def update(x=0.3):
    with fig.batch_update():
        bar.y=[x, 1-x]
fig

更新:

从 Plotly 4.0 开始,您需要指定 fig.data[0].y 而不是 bar.y.

From Plotly 4.0 you need to specify fig.data[0].y instead of bar.y.

这篇关于使用 Plotly 的 Slider 交互式绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆