在HTML表格中,如何使用python在jupyter笔记本中添加文字旁边的文字? [英] In an HTML table, how to add text beside plot in jupyter notebook using python?

查看:1369
本文介绍了在HTML表格中,如何使用python在jupyter笔记本中添加文字旁边的文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关如何创建1 X 2 HTML表格的任何想法,其中单元格{0}是matplotlib图和单元格{1}是Python 3.X的文本说明?

Any ideas on how to create a 1 X 2 HTML table where cell {0} is a matplotlib plot and cell {1} is a text description for 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)) 

设置测试用例:

Setting up a test case:

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



Then running the function in a Jupyter notebook:

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

我的输出如下:

My output is as follows:

然而,我有兴趣真正看到内嵌Jupyter笔记本的情节。

However, I am interested in actually seeing the plot inline a Jupyter notebook.

推荐答案

您似乎已阅读文件并通过使用 BytesIO 来进入正确的轨道。另外两个步骤是:

It seems that you've read the document and are on the right track by using BytesIO. Two more steps to do are just:


  1. 为您绘制一个适当的标签

  2. 编码您的 figdata 使用Base64。然后将它们解码为 str

  1. Use a proper tag for you plot
  2. Encode your figdata using Base64. Then decode them into str

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

Here is a complete and verifiable (in Jupyter notebook) example modified from your code:

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

这篇关于在HTML表格中,如何使用python在jupyter笔记本中添加文字旁边的文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆