混合使用matplotlib交互式图和内联图?

时间:2020-03-09 09:15:57

标签: python matplotlib jupyter-notebook

许多图不需要交互,因此我尝试将它们更改为嵌入式图。

我尝试了以下操作,但未成功:

  • plt.close(fig)。清楚数字

  • plt.ioff(),失败

  • %matplotlib inline %matplotlib notebook之间包装代码。它将关闭其他交互式地块

1 个答案:

答案 0 :(得分:2)

只能有一个后端处于活动状态。可以更改后端,但这将需要关闭交互式图形。

一个选项是始终使用交互式后端(例如%matplotlib widget)并调用自定义函数,该函数可在需要时内联显示png图像。

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

enter image description here

相关问题