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

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

关于如何创建一个 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')

我的输出如下: enter image description here

但是,我有兴趣在 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')

enter image description here

关于html - 在 HTML 表格中,如何使用 python 在 jupyter notebook 中的绘图旁边添加文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44741809/

相关文章:

html - 地铁风格中的 Div 位置

javascript - 包含在 div 中的相同文本在被 Javascript 插入后会溢出相同的 div

python - 向按年线分组的时间序列添加标签 - Matplotlib、Python

jquery - 进行了 CSS 更改,失去了功能

javascript - 使用按钮 Onclick 切换功能

python - Related Manager 一个方向为空,另一个方向为空

python - DeleteView 有 2 个争论帖子和用户

python - '\b' 在 Python 中如何工作?

python - Matplotlib 找不到 Facefile,正在使用旧的 Python 解释器位置

Python:在 matplot 散点图的 x 轴上绘制字符串会产生 "could not convert string to float"