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

查看:481
本文介绍了使用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.

Mathematica代码:

Mathematica code:

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


更新


UPDATE

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

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天全站免登陆