Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get python graph output into html webpage directly

I am using different libraries like pandas and numpy for generating a dataframe, which eventually generate a graph.

Now, I need to show this graph into a simple webpage which is in HTML.

Note: I am also willing to take 2-3 input from user in HTML page then pass that data to my python file. Afterwards, python file generates a graph based on given data(from HTML page) and I need to pass this graph to an HTML page.

df[[main_data]].plot()

Here, main_data is variable whose value is coming from HTML page. And I am doing python code in SPYDER. And I am not using any Framework.

like image 672
Jay Desai Avatar asked Feb 27 '18 18:02

Jay Desai


People also ask

How do I show Python output in HTML?

In order to display the HTML file as a python output, we will be using the codecs library. This library is used to open files which have a certain encoding. It takes a parameter encoding which makes it different from the built-in open() function.

How do I save my Matplotlib graph as HTML?

show() converts any Matplotlib plot to HTML and opens the figure in the web browser. mpld3. save_html(fig,'myfig. html') method saves figures to HTML files for archiving or uploading as an iframe to a website, etc.


1 Answers

This depends somewhat on what you mean by showing the graph as html. I can see a couple ways, the first and simplest is to save the figure as a PNG and then supply the path to the file in the html:

Python code:

import pandas as pd
import matplotlib.pyplot as plt

s = pd.Series([1, 2, 3])
fig, ax = plt.subplots()
s.plot.bar()
fig.savefig('my_plot.png')

HTML:

<img src='my_plot.png'/>

The second way would be to encode the figure as base64. This has the advantage of being portable, and the disadvantage of making very large unwieldy html files. I am not a web programmer, so there may be other caveats as well that I am not aware of.

python:

import io
import base64

def fig_to_base64(fig):
    img = io.BytesIO()
    fig.savefig(img, format='png',
                bbox_inches='tight')
    img.seek(0)

    return base64.b64encode(img.getvalue())

encoded = fig_to_base64(fig)
my_html = '<img src="data:image/png;base64, {}">'.format(encoded.decode('utf-8'))

my_html can be passed into you html file, or you can inject it with jinja2 or whatever you use. Here is SO post regarding viewing base64 in html https://stackoverflow.com/a/8499716/3639023 and encoding images as base64 How to convert PIL Image.image object to base64 string?

like image 133
johnchase Avatar answered Oct 07 '22 16:10

johnchase