【问题标题】:In an HTML table, how to add text beside plot in jupyter notebook using python?在 HTML 表格中,如何使用 python 在 jupyter notebook 中的绘图旁边添加文本?
【发布时间】:2017-11-28 05:40:34
【问题描述】:

关于如何创建一个 1 X 2 HTML 表格,其中单元格 {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 笔记本中实际查看情节。

【问题讨论】:

    标签: html python-3.x matplotlib jupyter-notebook bytesio


    【解决方案1】:

    您似乎已经阅读了document 并且使用BytesIO 走在正确的轨道上。还有两个步骤:

    1. 为您的绘图使用适当的标签
    2. 使用 Base64 对您的 figdata 进行编码。然后将它们解码为str

    这是一个从您的代码修改的完整且可验证的(在 Jupyter 笔记本中)示例:

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

    【讨论】:

      猜你喜欢
      • 2018-12-27
      • 2017-12-30
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      • 2023-02-02
      • 2022-12-15
      • 2020-02-11
      • 2016-08-17
      相关资源
      最近更新 更多