html - 将 matplotlib 图嵌入 iPython HTML

标签 html matplotlib ipython jupyter-notebook

我想在 Jupyter Notebook 中使用代码单元动态编写和显示 HTML。目标是生成 HTML 以我选择的某种方式显示 table、div、img 标签。我想捕获 img 数据并将其放在这个自动生成的 HTML 中我想要的位置。

到目前为止,我发现我可以执行以下操作:

from IPython.core.display import HTML

HTML("<h1>Hello</h1>")

并得到:

你好

那太棒了。但是,我希望能够做到这一点:
HTML("<h1>Hello</h1><hr/><img src='somestring'/>")

并得到类似于 的东西您好 带有一条水平线和其下方的图像,其中图像与下图相同。
import pandas as pd
import numpy as np

np.random.seed(314)
df = pd.DataFrame(np.random.randn(1000, 2), columns=['x', 'y'])

df.plot.scatter(0, 1)

enter image description here

结果应如下所示:

enter image description here



我要更换什么 'something'为了实现这一点?更重要的是,我如何通过 python 获取它?

我会想象图形对象上有一个属性可以保存图像的序列化版本,但我找不到它。

最佳答案

经过一番挖掘。感谢 Dmitry B. 为我指明了正确的方向。

解决方案

from IPython.core.display import HTML
import binascii
from StringIO import StringIO
import matplotlib.pyplot as plt

# open IO object
sio = StringIO()

# generate random DataFrame
np.random.seed(314)
df = pd.DataFrame(np.random.randn(1000, 2), columns=['x', 'y'])

# initialize figure and axis
fig, ax = plt.subplots(1, 1)

# plot DataFrame
ax.scatter(df.iloc[:, 0], df.iloc[:, 1]);

# print raw canvas data to IO object
fig.canvas.print_png(sio)

# convert raw binary data to base64
# I use this to embed in an img tag
img_data = binascii.b2a_base64(sio.getvalue())

# keep img tag outter html in its own variable
img_html = '<img src="data:image/png;base64,{}&#10;">'.format(img_data)

HTML("<h1>Hello</h1><hr/>"+img_html)

我最终得到:

enter image description here

关于html - 将 matplotlib 图嵌入 iPython HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36991600/

相关文章:

python - 如何像 jupyter notebook 的默认单元格输出一样打印

python - 如何在一个单元格内的 ipython 笔记本中循环更新两个子图

python - tkinter 和 matplotlib : windows not showing until program closes under Linux

python - 在Python中,如何使用matplotlib保存方形图像?

html - 初学者 html 问题::如何让水平滚动条出现?他们只是不会.. td 标签中的数据正在移动到下一行

javascript - 转义序列化字符串中的#符号

python - 无法绘制图表 : matplotlib is needed for plotting

python - 如何在没有终端提示的情况下从 IPython session 中复制

javascript - CSS 旋转、最终帧和内联 block

html - CSS 背景图像 url() 在各种浏览器中未显示错误 '404 not found'