python - Jupyter 与 ipywidgets 和plotly v4?

标签 python jupyter-notebook plotly ipywidgets

在 Windows 10 上使用 Anaconda 安装的 Jupyter;还安装了conda install -cplotlyplotly,并且显然得到了Plotly v4。

我只想从一个简单的例子开始 - 并使用 ipywidget slider 而不是 Plotly slider 。所以,我发现:

https://moderndata.plot.ly/widgets-in-ipython-notebook-and-plotly/

EXAMPLE 3: interact

A simple example of using the interact decorator from ipywidgets to create a simple set of widgets to control the parameters of a plot.

Link to IPython notebook

对 - 所以我转到该链接,并将其中的代码重新组织为:

import plotly.graph_objs as go
import numpy as np
from ipywidgets import interact

fig = go.FigureWidget()
scatt = fig.add_scatter()

xs=np.linspace(0, 6, 100)
fig.show()

@interact(a=(1.0, 4.0, 0.01), b=(0, 10.0, 0.01), color=['red', 'green', 'blue'])
def update(a=3.6, b=4.3, color='blue'):
    with fig.batch_update():
        scatt.x=xs
        scatt.y=np.sin(a*xs-b)
        scatt.line.color=color

...当我运行这个单元格时,它会绘制一个空图:

jupyter_plotly_fail.png

...失败并显示:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\ipywidgets\widgets\interaction.py in update(self, *args)
    254                     value = widget.get_interact_value()
    255                     self.kwargs[widget._kwarg] = value
--> 256                 self.result = self.f(**self.kwargs)
    257                 show_inline_matplotlib_plots()
    258                 if self.auto_display and self.result is not None:

<ipython-input-21-7dcd6b5f2be1> in update(a, b, color)
     12 def update(a=3.6, b=4.3, color='blue'):
     13     with fig.batch_update():
---> 14         scatt.x=xs
     15         scatt.y=np.sin(a*xs-b)
     16         scatt.line.color=color

C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setattr__(self, prop, value)
    349         else:
    350             # Raise error on unknown public properties
--> 351             raise AttributeError(prop)
    352 
    353     def __getitem__(self, prop):

AttributeError: x

显然,这是因为 Plotly v4 中有足够的更改来保证 Version 4 migration guide | plotly ;浏览了一下,我尝试修改代码,如下所示:

import plotly.graph_objs as go
import numpy as np
from ipywidgets import interact

fig = go.FigureWidget()
scattf = fig.add_scatter()
scatt = scattf.data[-1]

xs=np.linspace(0, 6, 100)
scattf.show()

@interact(a=(1.0, 4.0, 0.01), b=(0, 10.0, 0.01), color=['red', 'green', 'blue'])
def update(a=3.6, b=4.3, color='blue'):
    with fig.batch_update():
        scatt.x=xs
        scatt.y=np.sin(a*xs-b)
        scatt.line.color=color

...现在我不再收到错误 - 但绘图仍然为空,并且当我拖动 slider 时不会更新。

有人可以告诉我,如何让这个示例正常工作,以便在拖动 slider 时绘制绘图并更新/重绘吗?

<小时/>

编辑:有点困惑,现在我有这个代码:

import plotly.graph_objs as go
import numpy as np
from ipywidgets import interact

fig = go.FigureWidget()
scattf = fig.add_scatter()
scatt = scattf.data[-1]

xs=np.linspace(0, 6, 100)
#scattf.show() # adds extra plot, if there is scattf.show() in update()!

@interact(a=(1.0, 4.0, 0.01), b=(0, 10.0, 0.01), color=['red', 'green', 'blue'])
def update(a=3.6, b=4.3, color='blue'):
    with fig.batch_update():
        scatt.x=xs
        scatt.y=np.sin(a*xs-b)
        scatt.line.color=color
        scattf.show()

update() # update once; so we don't get empty plot at start? not really - still getting empty plot at start, and another one after which is updated

这里有两个问题:

  • 运行单元格后,第一个绘制的图为空,然后绘制了另一个图 - 如何让它仅使用默认值绘制一个图? (如果没有最后一个 update(),则只有一个图,但一开始是空的 - 并且必须拖动 slider 才能开始绘制)
  • 现在,拖动 slider 时绘图会发生变化 - 但它会频繁闪烁;有什么方法可以减少闪烁吗?

最佳答案

对了,所以找到了Interactive Data Analysis with FigureWidget ipywidgets - 并相应地重写示例;这有更平滑的响应,并且没有双重绘制 - 但是,我仍然不确定这是否是这样做的方法;所以如果有人知道更好,请发布...

import plotly.graph_objs as go
import numpy as np
#from ipywidgets import interact, interactive
from ipywidgets import widgets
from IPython.display import display

aSlider = widgets.FloatSlider(
    value=2.0,
    min=1.0,
    max=4.0,
    step=0.01,
    description='a:',
    continuous_update=False
)

bSlider = widgets.FloatSlider(
    value=1.0,
    min=0.0,
    max=10.0,
    step=0.01,
    description='b:',
    continuous_update=True
)

colorDropdown = widgets.Dropdown(
    description='Color:',
    value='blue',
    options=['red', 'blue', 'green']
)

fig = go.FigureWidget()
#fig.show()
scattf = fig.add_scatter()
scatt = scattf.data[-1]

xs=np.linspace(0, 6, 100)

def response(change):
    with fig.batch_update():
        fig.data[0].x=xs
        fig.data[0].y=np.sin(aSlider.value*xs-bSlider.value)
        fig.data[0].line.color=colorDropdown.value
        fig.layout.xaxis.title = 'whatever'

aSlider.observe(response, names="value")
bSlider.observe(response, names="value")
colorDropdown.observe(response, names="value")

response("doesn't matter what I send here, just triggering") # MUST be before widgets.VBox - if response(x) is last, NOTHING is drawn! 

widgets.VBox([aSlider,
              bSlider,
              colorDropdown,
              fig])

关于python - Jupyter 与 ipywidgets 和plotly v4?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57220263/

相关文章:

python - 无法在电子邮件中添加附件

python - 在 pandas 中检查一个数据帧与另一个数据帧的值的快速方法

r - crosstalk的filter_select不会过滤图表

r - 我可以在绘图中重新创建这个极坐标蜘蛛图吗?

python - 依次运行多个命令行 linux python

python - 使用 RDFLib 获取 SPARQL 查询中的相交类

python - 使用 %matplotlib 笔记本时图形被省略并缩进

python - Mac 上的 Jupyter : run files from non-default directory

python - 使用 Pytesseract/OpenCV 绘制边界框

python - plotly - 无法使用 bar_mpl() 在离线模式下绘制条形图