gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:18:36 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com