在 HTML table 中,如何使用 python 在 jupyter notebook 的绘图旁边添加文本?

In an HTML table, how to add text beside plot in jupyter notebook using python?

关于如何创建 1 X 2 HTML table 的任何想法,其中单元格 {0} 是 matplotlib 图,单元格 {1} 是 Python 3.X?

import matplotlib.pyplot as plt
from io import BytesIO
%matplotlib inline

def add_split_screen(fig, text, iwidth=None):

    figdata = BytesIO()
    fig.savefig(figdata, format='png') 
    figdata.seek(0)
    figdata
    figdata.close()
    iwidth = ' width={0} '.format(iwidth) if iwidth is not None else ''
    datatable = '<table><tr><td>{0}</td><td>{1}</td></tr></table>'.format(figdata, text)
    display(HTML(datatable)) 

设置测试用例:

fig, ax = plt.subplots(1,1, figsize=(6,4))
ax.plot([1,2,3])
text = '<h4>Special Chart:</h4><BR>Description of chart will go here.'

然后 运行 Jupyter notebook 中的函数:

add_split_screen(fig, text, iwidth='500px')

我的输出如下:

但是,我有兴趣在 Jupyter notebook 中实际看到情节。

看来您已经阅读了 document,并且使用 BytesIO 的方法是正确的。还有两步要做:

  1. 为你的情节使用合适的标签
  2. 使用 Base64 对您的 figdata 进行编码。然后解码成str

这是根据您的代码修改的完整且可验证的(在 Jupyter notebook 中)示例:

from base64 import b64encode
from io import BytesIO

from IPython.display import display, HTML
import matplotlib.pyplot as plt

def add_split_screen(fig, text, iwidth=None):
    figdata = BytesIO()
    fig.savefig(figdata, format='png')
    iwidth = ' width={0} '.format(iwidth) if iwidth is not None else ''
    datatable = '<table><tr><td><img src="data:image/png;base64,{0}"/></td><td>{1}</td></tr></table>'.format(b64encode(figdata.getvalue()).decode(), text)
    display(HTML(datatable)) 

fig, ax = plt.subplots(1,1, figsize=(6,4))
ax.plot([1,2,3])
text = '<h4>Special Chart:</h4><BR>Description of chart will go here.'
add_split_screen(fig, text, iwidth='500px')