如何在Jupyter/IPython Notebook中将文本段落显示在图像旁边

3
我正在寻找一种(或许是创意性的)方法,在Jupyter Notebook中将文本放在图表旁边。想法是在图表旁边有一个详细的描述,而不是笔记本通常的垂直流程。
有任何想法吗?
1个回答

8
一种相当有创意的方法是模仿内联后端,但添加一个基础表格。对于Python 2.7,可能的解决方案如下:
from io import BytesIO
import matplotlib.pyplot as plt
from IPython.display import display, Image, HTML
import base64

def plotdesc(fig, text, iwidth=None):
    bio = BytesIO()
    # save fig as png to bytes IO instead to disk
    fig.savefig(bio, format='png')
    plt.close(fig)
    iwidth = ' width={0} '.format(iwidth) if iwidth is not None else ''
    img_tag = "<img src='data:image/png;base64," + base64.b64encode(bio.getvalue()) + "'{0}/>".format(iwidth)
    datatable = '<table><tr><td>{0}</td><td>{1}</td></tr></table>'.format(img_tag, text)
    display(HTML(datatable))

使用方法:

fig, ax = plt.subplots(1,1, figsize=(6,4))
ax.plot([1,2,3])
text = '<h4>Description of the chart:</h4><BR>asdfsa fasdf qwer fsdaf er qw asdcdsafqwer dacfas dfqwetr cvxy fsa'
plotdesc(fig, text, iwidth='500px')

如果您现在将表格CSS设置为删除边框,例如:
%%html
<style>
table,td,tr,th {border:none!important}
</style>

您会得到一个像这样的图:
enter image description here
当然,此解决方案可以进一步改进以使用固定列宽等功能。如果我没记错,在Python 3.x中,base64编码略有不同。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接