In an HTML table, how to add text beside plot in jupyter notebook using python?

有些话、适合烂在心里 提交于 2019-12-20 07:24:57

问题


Any ideas on how to create a 1 X 2 HTML table where cell {0} is a matplotlib plot and cell {1} is a text description for 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)) 

Setting up a test case:

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

Then running the function in a Jupyter notebook:

add_split_screen(fig, text, iwidth='500px')

My output is as follows:

However, I am interested in actually seeing the plot inline a Jupyter notebook.


回答1:


It seems that you've read the document and are on the right track by using BytesIO. Two more steps to do are just:

  1. Use a proper tag for you plot
  2. Encode your figdata using Base64. Then decode them into str

Here is a complete and verifiable (in Jupyter notebook) example modified from your code:

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



来源:https://stackoverflow.com/questions/44741809/in-an-html-table-how-to-add-text-beside-plot-in-jupyter-notebook-using-python

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