Creando un histograma interactivo con Matplotlib

Beginner

This tutorial is from open-source community. Access the source code

Introducción

En este laboratorio, aprenderemos a crear un histograma interactivo utilizando Matplotlib. La interactividad está codificada en ECMAScript (JavaScript) y se inserta en el código SVG en un paso de post-procesamiento. El histograma resultante tendrá barras que se pueden ocultar o mostrar haciendo clic en los marcadores de la leyenda.

Consejos sobre la VM

Una vez finalizada la inicialización de la VM, haga clic en la esquina superior izquierda para cambiar a la pestaña Cuaderno y acceder a Jupyter Notebook para practicar.

A veces, es posible que tenga que esperar unos segundos a que Jupyter Notebook termine de cargarse. La validación de operaciones no se puede automatizar debido a las limitaciones de Jupyter Notebook.

Si tiene problemas durante el aprendizaje, no dude en preguntar a Labby. Deje su retroalimentación después de la sesión y resolveremos rápidamente el problema para usted.

Crear el histograma, la leyenda y el título

Primero, crearemos el histograma, la leyenda y el título utilizando Matplotlib. También asignaremos IDs a cada objeto utilizando el método set_gid(). Esto ayudará a relacionar los objetos de Matplotlib creados en Python y las estructuras SVG correspondientes que se analizan en el segundo paso.

import matplotlib.pyplot as plt
import numpy as np

## Fixing random state for reproducibility
np.random.seed(19680801)

## Create histogram, legend, and title
plt.figure()
r = np.random.randn(100)
r1 = r + 1
labels = ['Rabbits', 'Frogs']
H = plt.hist([r, r1], label=labels)
containers = H[-1]
leg = plt.legend(frameon=False)
plt.title("From a web browser, click on the legend\n"
          "marker to toggle the corresponding histogram.")

## Assign IDs to the SVG objects we'll modify
hist_patches = {}
for ic, c in enumerate(containers):
    hist_patches[f'hist_{ic}'] = []
    for il, element in enumerate(c):
        element.set_gid(f'hist_{ic}_patch_{il}')
        hist_patches[f'hist_{ic}'].append(f'hist_{ic}_patch_{il}')

## Set IDs for the legend patches
for i, t in enumerate(leg.get_patches()):
    t.set_gid(f'leg_patch_{i}')

## Set IDs for the text patches
for i, t in enumerate(leg.get_texts()):
    t.set_gid(f'leg_text_{i}')

Agregar interactividad al histograma

A continuación, agregaremos interactividad al histograma modificando el código SVG utilizando ECMAScript (JavaScript). Agregaremos atributos a los objetos de parche y texto utilizando el método set(). También crearemos una variable global container que almacena los IDs de los parches pertenecientes a cada histograma. Finalmente, crearemos una función toggle_hist() que establece el atributo de visibilidad de todos los parches de cada histograma y la opacidad del marcador en sí mismo.

from io import BytesIO
import json
import xml.etree.ElementTree as ET

plt.rcParams['svg.fonttype'] = 'none'

## Save SVG in a fake file object
f = BytesIO()
plt.savefig(f, format="svg")

## Create XML tree from the SVG file
tree, xmlid = ET.XMLID(f.getvalue())

## Add attributes to the patch objects
for i, t in enumerate(leg.get_patches()):
    el = xmlid[f'leg_patch_{i}']
    el.set('cursor', 'pointer')
    el.set('onclick', "toggle_hist(this)")

## Add attributes to the text objects
for i, t in enumerate(leg.get_texts()):
    el = xmlid[f'leg_text_{i}']
    el.set('cursor', 'pointer')
    el.set('onclick', "toggle_hist(this)")

## Create script defining the function `toggle_hist`
script = """
<script type="text/ecmascript">
<![CDATA[
var container = %s

function toggle(oid, attribute, values) {
    /* Toggle the style attribute of an object between two values.

    Parameters
    ----------
    oid : str
      Object identifier.
    attribute : str
      Name of style attribute.
    values : [on state, off state]
      The two values that are switched between.
    */
    var obj = document.getElementById(oid);
    var a = obj.style[attribute];

    a = (a == values[0] || a == "")? values[1] : values[0];
    obj.style[attribute] = a;
    }

function toggle_hist(obj) {

    var num = obj.id.slice(-1);

    toggle('leg_patch_' + num, 'opacity', [1, 0.3]);
    toggle('leg_text_' + num, 'opacity', [1, 0.5]);

    var names = container['hist_'+num]

    for (var i=0; i < names.length; i++) {
        toggle(names[i], 'opacity', [1, 0])
    };
    }
]]>
</script>
""" % json.dumps(hist_patches)

## Add a transition effect
css = tree.find('.//{http://www.w3.org/2000/svg}style')
css.text = css.text + "g {-webkit-transition:opacity 0.4s ease-out;" + \
    "-moz-transition:opacity 0.4s ease-out;}"

## Insert the script and save to file
tree.insert(0, ET.XML(script))
ET.ElementTree(tree).write("svg_histogram.svg")

Ver el histograma interactivo

Finalmente, podemos ver el histograma interactivo abriendo el archivo SVG en un navegador web. Para ocultar o mostrar las barras, simplemente haga clic en los marcadores de la leyenda.

Resumen

En este laboratorio, aprendimos a crear un histograma interactivo utilizando Matplotlib. Utilizamos ECMAScript (JavaScript) para agregar interactividad al histograma modificando el código SVG. El histograma resultante tiene barras que se pueden ocultar o mostrar haciendo clic en los marcadores de la leyenda.