Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

python - Using %matplotlib notebook after %matplotlib inline in Jupyter Notebook doesn't work

I am using Jupyter Notebook for plotting piechart figures.

In first cell with my code I have a magic command %matplotlib inline and after this magic command I run my code, everything works fine and my figure renders.

But in second cell when I set %matplotlib notebook for interactive plotting my figure won't render after running this second cell.

I need to restart kernel and run cell with %matplotlib notebook again and cannot run %matplotlib inline command before that.

Here is my code for first cell with %matplotlib inline, which renders fine:

import matplotlib.pyplot as plt

%matplotlib inline

labels = "No", "Yes"
sizes = [100, 50]

fig, ax = plt.subplots(figsize=(6, 6))

_, texts, autotexts = ax.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%',
             shadow=False, startangle=90)

ax.axis('equal')

After that I have second cell with same code, just %matplotlib inline is changed to %matplotlib notebook. Figure won't render after I run this cell and I need to restart kernel and run this cell again.

Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just have the wrong order of your commands. A backend should be set before importing pyplot in jupyter. Or in other words, after changing the backend, pyplot needs to be imported again.

Therefore call %matplotlib ... prior to importing pyplot.

In first cell:

%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1,1.6,3])

In second cell:

%matplotlib notebook
#calling it a second time may prevent some graphics errors
%matplotlib notebook  
import matplotlib.pyplot as plt
plt.plot([1,1.6,3])


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...