简体   繁体   中英

Jupyter Notebook matplotlib notebook makes plot not show up, inline makes it not interactive

I have one python file Vis.py with the following two functions:

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();

and I am trying to use the plot_test function in a separate ipynb file:

%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)

However, the plot doesn't show up, not even an empty white space. I tried running %matplotlib inline before plot_test(s) . That makes the plot show up, but it also gets rid of the interactiveness of the plot.

The updating function references ax , which is out of scope. A solution is to put the updating function inside the plot_test function.

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()

Then, keeping the notebook part unchanged,

%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)

results in the desired interactive figure for me.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM