How to display a text paragraph next to figure in jupyter/ipython notebook

天大地大妈咪最大 提交于 2020-01-13 04:53:11

问题


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.

Any ideas?


回答1:


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))

To be used like:

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')

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

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.



来源:https://stackoverflow.com/questions/32423322/how-to-display-a-text-paragraph-next-to-figure-in-jupyter-ipython-notebook

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!