Jupyter Notebook matplotlib笔记本使绘图不显示,内联使其不交互式

时间:2019-05-07 00:05:29

标签: python python-3.x matplotlib jupyter-notebook

我有一个带有以下两个功能的python文件Vis.py

import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

def update(val): #needed for slider function of plot_test
    pos = spos.val
    ax.axis([pos,pos+10,-1,1])
    fig.canvas.draw_idle()

def plot_test(data):
    fig, ax = plt.subplots()
    plt.subplots_adjust(bottom=0.25)
    plt.plot(data)
    plt.axis([0, 10, -1, 1])
    axcolor = 'lightgoldenrodyellow'
    axpos = plt.axes([0.2, 0.1, 0.65, 0.03], facecolor=axcolor)
    spos = Slider(axpos, 'Pos', 0.1, 90.0)
    spos.on_changed(update)
    plt.show();

我正在尝试在单独的ipynb文件中使用plot_test函数:

%matplotlib notebook
from Vis import *
import numpy as np

t = np.arange(0.0, 200.0, 0.1)
s = np.sin(2*np.pi*t)
plot_test(s)

但是,该图没有显示,甚至没有空白。我尝试在%matplotlib inline之前运行plot_test(s)。这样可以显示情节,但是也摆脱了情节的互动性。

1 个答案:

答案 0 :(得分:1)

更新函数引用ax,这超出范围。一种解决方案是将更新功能放在plot_test函数中。

import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

def plot_test(data):
    fig, ax = plt.subplots()
    plt.subplots_adjust(bottom=0.25)
    plt.plot(data)
    plt.axis([0, 10, -1, 1])
    axcolor = 'lightgoldenrodyellow'
    axpos = plt.axes([0.2, 0.1, 0.65, 0.03], facecolor=axcolor)
    spos = Slider(axpos, 'Pos', 0.1, 90.0)

    def update(val): #needed for slider function of plot_test
        pos = spos.val
        ax.axis([pos,pos+10,-1,1])
        fig.canvas.draw_idle()

    spos.on_changed(update)
    plt.show()

然后,保持笔记本部件不变

%matplotlib notebook
from Vis import *
import numpy as np

t = np.arange(0.0, 200.0, 0.1)
s = np.sin(2*np.pi*t)
plot_test(s)

为我带来所需的互动人物。

enter image description here