【问题标题】:IPython Notebook: How to combine HTML output and matplotlib figures?IPython Notebook:如何结合 HTML 输出和 matplotlib 图形?
【发布时间】:2015-05-06 19:35:43
【问题描述】:
以下代码在 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)
如何使用这种方法将 matplotlib 动态生成的图形包含在 HTML 布局中?
【问题讨论】:
标签:
python
html
matplotlib
ipython
ipython-notebook
【解决方案1】:
另一种选择是遵循此博客上的建议:http://protips.maxmasnick.com/hide-code-when-sharing-ipython-notebooks
具体来说:
- 将此代码复制到 IPython 笔记本的顶部(第一个单元格)(直接从上面的链接复制代码和 cmets,所有功劳归博主所有):
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)
运行顶部单元格(其中包含上述代码)。当它完成执行时,您应该会看到它正下方的“切换代码”按钮。
单击按钮可关闭/打开代码。相同的切换行为将出现在 .ipynb 以及转换后的 .html 中。
【解决方案2】:
由于 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)
【解决方案3】:
如果你只是想结合html输出和绘图,那么开头某处的神奇命令%matplotlib inline就足够了。
当您以 html 格式下载笔记本时,所有绘图都将被正确编码并包含在您的单个 html 文件中。