Skip to content

Instantly share code, notes, and snippets.

@1N0T
Created May 12, 2019 11:32
Show Gist options
  • Save 1N0T/bb7ca80c39834c4a2938ee4025cb553c to your computer and use it in GitHub Desktop.
Save 1N0T/bb7ca80c39834c4a2938ee4025cb553c to your computer and use it in GitHub Desktop.
(python) Ejemplo de publicación en bottle de una gráfica generada siguiendo el mismo proceso que se seguiríamos para crearla en un jupyter notebook.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Ejemplo de publicación en flask de una gráfica generada siguiendo el
# mismo proceso que se seguiríamos para crearla en un jupyter notebook
# Paquetes requeridos
# sudo apt install python3-tk
# python3 -m venv venv
# source venv/bin/activate
# pip3 install matplotlib
# pip3 install pandas
# pip3 install numpy
# pip3 install bottle
# python3 bottle_pandas_matplotlib.py
# http://localhost:6789/plot.png
import os
import io
from bottle import (route, run, request, response, abort, error, static_file)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#===============================================================================
# Configuramos directorios.
#===============================================================================
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, 'static')
#===============================================================================
# Mapeamos el contenido estático.
#===============================================================================
@route('/plot.png')
def dibuja_grafico():
df = pd.DataFrame({
'nombre':['José','María','Pedro','Jeff','Manuel','Lisa','Antonio'],
'edad':[23,78,22,19,45,33,20],
'genero':['M','F','M','M','M','F','M'],
'provincia':['Madrid','Barcelona','Málaga', 'Lérida','Valencia','París','Lugo'],
'num_hijos':[2,0,0,3,2,1,4],
'num_mascotas':[5,1,0,5,2,2,3]
})
df.plot(figsize=(16, 8), title='Gráfico de ejemplo', kind='bar', stacked=False)
output = io.BytesIO()
plt.legend()
plt.savefig(output, format='png')
response.set_header('Content-type', 'image/png')
return output.getvalue()
#===============================================================================
# Iniciamos el servidor web que expone las funciones en todas sus direcciones
# de red.
#===============================================================================
run(reloader = True, debug = True, host = "0.0.0.0", port = 6789)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment