2016-07-22 49 views
0

如何使用Jupyter Notebook高效顯示ipywidgets的類似圖表?如何高效地用ipywidgets替換陰謀中的元素?

我希望交互式地繪製一個沉重的情節(重要的是它有很多數據點,需要一些時間來繪製它),並使用ipywidgets進行交互而不用重新繪製所有複雜情節來修改它的單個元素。有內置功能來做到這一點嗎?

基本上就是我想要做的是

import numpy as np 
import matplotlib.pyplot as plt 
from ipywidgets import interact 
import matplotlib.patches as patches 
%matplotlib inline #ideally nbagg 

def complicated plot(t): 
    plt.plot(HEAVY_DATA_SET) 
    ax = plt.gca() 
    p = patches.Rectangle(something_that_depends_on_t) 
    ax.add_patch(p) 

interact(complicatedplot, t=(1, 100)); 

現在最多需要2秒每個重繪。我希望有辦法保持這個數字,只是替換那個矩形。

黑客可能會創建一個常量部分的圖形,將其作爲背景並繪製矩形部分。但聲音太骯髒

謝謝

+0

你可以添加更多關於你真正想做什麼的細節嗎?例如,在散點圖中,如果您的圖在「p」變量中被引用,您可以執行「p.set_offsets」重新定義數據。也許你可以做一些像'ax.get_children()'和修改其中一個對象。對於小部件,我認爲ipywidgets有一個'observe'方法,您可以在其中定義要更新的函數,在您的情況下,您可以定義修改您的圖的函數 –

+0

我想顯示100行圖(plt.plot(HEAVY_DATA_SET) ),然後在這些行的頂部添加一個垂直矩形。 – gota

+0

也許你可以從'ax.get_children()'中刪除矩形,然後重繪矩形?例如,如果你調用'ax.get_children()',你會在列表中看到一些'

回答

1

這是一個互動的方式來改變矩形寬度的粗糙例子(我假設你是在IPython的或Jupyter筆記本):

import matplotlib 
import matplotlib.pyplot as plt 
import matplotlib.patches as patches 

import ipywidgets 
from IPython.display import display 

%matplotlib nbagg 

f = plt.figure() 
ax = plt.gca() 

ax.add_patch(
    patches.Rectangle(
     (0.1, 0.1), # (x,y) 
     0.5,   # width 
     0.5,   # height 
    ) 
) 

# There must be an easier way to reference the rectangle 
rect = ax.get_children()[0] 

# Create a slider widget 
my_widget = ipywidgets.FloatSlider(value=0.5, min=0.1, max=1, step=0.1, description=('Slider')) 

# This function will be called when the slider changes 
# It takes the current value of the slider 
def change_rectangle_width(): 
    rect.set_width(my_widget.value) 
    plt.draw() 

# Now define what is called when the slider changes 
my_widget.on_trait_change(change_rectangle_width) 

# Show the slider 
display(my_widget) 

然後,如果您移動滑塊,矩形的寬度將會改變。我會盡量整理代碼,但你可能有想法。要更改座標,您必須執行rect.xy = (x0, y0),其中x0y0是新座標。