我正在寻找一种(可能是创造性的)方式来在 jupyter 笔记本中的图表旁边放置文本。这个想法是在图表旁边有一个图表的详细描述,而不是笔记本的通常垂直流动。

有任何想法吗?

最佳答案

一个相当有创意的方法是模仿内联后端,但添加一个底层表。 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>

你得到一个像
ipython - 如何在 jupyter/ipython notebook 中的数字旁边显示文本段落-LMLPHP

当然,可以进一步增强此解决方案以使用固定列宽等。
IIRC base64 编码与 python 3.x 略有不同。

关于ipython - 如何在 jupyter/ipython notebook 中的数字旁边显示文本段落,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32423322/

10-11 07:42