Dans une table HTML, comment ajouter du texte à côté de l'intrigue dans le carnet jupyter en utilisant python?

N'importe quelles idées sur la façon de créer une table HTML 1 X 2 où la cellule {0} est une parcelle de terrain de matplotlib et la cellule {1} est une description de texte pour 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)) 

mise en place d'un boîtier d'essai:

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

alors en cours d'exécution de la fonction dans un carnet Jupyter:

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

ma sortie est la suivante: enter image description here

Cependant, je suis intéressé en fait voir l'intrigue dans un carnet Jupyter.

0
demandé sur Student 2017-06-25 02:19:18

1 réponses

il semble que vous avez lu le document et êtes sur la bonne voie en utilisant BytesIO . Deux autres étapes à franchir sont tout simplement:

  1. utilisez une étiquette appropriée pour votre parcelle
  2. encodez votre figdata en utilisant Base64. Puis les décoder en str

voici un exemple complet et vérifiable (dans le carnet de notes de Jupyter) modifié à partir de votre 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')

enter image description here

1
répondu Y. Luo 2017-06-25 05:45:12