简体   繁体   中英

Mix matplotlib interactive and inline plots?

Many plots just doesn't need to be interactive so I tried to change them to inline plots.

I tried the following without success:

  • plt.close(fig) . It clear the figure

  • plt.ioff() , failed

  • wrap codes between %matplotlib inline %matplotlib notebook . It close other interactive plots

There can only ever be one single backend be active. It would be possible to change the backend, but that would require to close the interactive figures.

An option is to work with interactive backend throughout (eg %matplotlib widget ) and call a custom function that shows a png image inline once that is desired.

#Cell1
%matplotlib widget

#Cell2
import matplotlib.pyplot as plt


def fig2inline(fig):
    from IPython.display import display, Image
    from io import BytesIO
    plt.close(fig)
    buff = BytesIO()
    fig.savefig(buff, format='png')
    buff.seek(0) 
    display(Image(data=buff.getvalue()))

#Cell3: (show the interactive plot)
fig, ax = plt.subplots(figsize=(3, 1.7))
ax.plot([1,3,4]);

#Cell4: (show the inline plot)
fig2, ax2 = plt.subplots(figsize=(3, 1.7))
ax2.plot([3,1,1]);
fig2inline(fig2)

在此处输入图片说明

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