如何在jupyter / ipython笔记本中显示图旁边的文本段落 [英] How to display a text paragraph next to figure in jupyter/ipython notebook
问题描述
我正在寻找一种(可能是创造性的)方式将文本放在jupyter笔记本中的图形旁边。我们的想法是对图表进行详细描述,而不是通常的笔记本垂直流程。
I am looking for a (perhaps creative) way to place text next to a graph in the jupyter notebook. The idea is to have a detailed description of the chart, right next to it, instead of the usual vertical flow of the notebook.
任何想法?
推荐答案
一种颇具创造性的方法是模仿内联后端,但添加基础表。 python 2.7的一个可能的解决方案看起来像
A rather creative way is to mimic the inline backend but adding a underlying table. A possible solution for python 2.7 could look like
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设置为删除边框例如
If you now set the table CSS to remove the border e.g.
%%html
<style>
table,td,tr,th {border:none!important}
</style>
你得到的情节如
you get a plot like
当然这个解决方案可以进一步增强以使用固定的列宽等。
IIRC base64编码与python 3.x略有不同。
Of course this solution can be further enhanced to use fixed column widths, etc. IIRC the base64 encoding was slightly different with python 3.x.
这篇关于如何在jupyter / ipython笔记本中显示图旁边的文本段落的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!