IPython Notebook:如何结合HTML输出和matplotlib图形?

8
以下代码将在IPython命令的结果单元格中输出渲染后的HTML:
from IPython.core.display import HTML

def putHTML():
    source = """
    <h1>Yah, rendered HTML</h1>
    <h2>Here is an image</h2>
    <img src="http://lbkbd.in/wp-content/uploads/2014/10/HTML-Logo.png"/>
    """
    return HTML(source)

enter image description here

我该如何使用这种方法在HTML布局中实时包含由matplotlib生成的图形?


这个解决方案在这里 https://dev59.com/62Uq5IYBdhLWcg3wEcNZ 似乎是正确的。然而,我需要将这个解决方案更新到 Python 3,并且使用 sio 作为一个 io.StringIO 对象的 plt.savefig(sio) 不起作用。 - clstaudt
3个回答

12

由于IPython已经有一个生成图像HTML输出的后端,因此您可以使用他们的内联后端:

from matplotlib._pylab_helpers import Gcf
from IPython.core.pylabtools import print_figure 
from base64 import b64encode

# Plot something
plot([1,2],[3,4])

# Get a handle for the plot that was just generated
fig = Gcf.get_all_fig_managers()[-1].canvas.figure

# Generate a data URL for the image
# Matplotlib's display() would output the plot, so I do this manually.
# There might be a wrapper for this somewhere in IPython, if you're
# unhappy with this line..
image_data = "data:image/png;base64,%s" % b64encode(print_figure(fig)).decode("utf-8")

# Remove the plot from the list of plots for the current cell
Gcf.destroy_fig(fig)

# Now you can use the data URL in your HTML output
HTML("Foo Bar <br> <img src='%s'> <br> Baz" % image_data)

0
另一种选择是遵循这篇博客的建议:http://protips.maxmasnick.com/hide-code-when-sharing-ipython-notebooks 具体来说:
  1. 将此代码复制到IPython笔记本的顶部(第一个单元格)中(从上面的链接直接复制代码和注释,所有功劳归博主所有):

import IPython.core.display as di

该行将在导出为HTML时默认隐藏代码:

di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True)

此行将添加一个用于切换代码块可见性的按钮,供HTML版本使用:

di.display_html('''<button onclick="jQuery('.input_area').toggle(); jQuery('.prompt').toggle();">Toggle code</button>''', raw=True)

  1. 运行顶部的单元格(其中包含上述代码)。执行完成后,您应该会看到“切换代码”按钮出现在其正下方。

  2. 单击按钮以切换代码的开/关状态。这种切换行为将同时出现在 .ipynb 和转换后的 .html 文件中。


-2

如果您只想将HTML输出和图形组合在一起,那么在开头的某个地方使用神奇的命令%matplotlib inline就足够了。

当您将笔记本下载为HTML时,所有的图形都将被正确编码并包含在单个HTML文件中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接