How to get python graph output into html webpage directly

半城伤御伤魂 提交于 2021-02-18 05:25:46

问题


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.


回答1:


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?




回答2:


The best way to export matplotlib charts to the web browser is to Use mpld3 library. Here is the example.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import mpld3
from mpld3 import plugins
np.random.seed(9615)

# generate df
N = 100
df = pd.DataFrame((.1 * (np.random.random((N, 5)) - .5)).cumsum(0),
                  columns=['a', 'b', 'c', 'd', 'e'],)

# plot line + confidence interval
fig, ax = plt.subplots()
ax.grid(True, alpha=0.3)

for key, val in df.iteritems():
    l, = ax.plot(val.index, val.values, label=key)
    ax.fill_between(val.index,
                    val.values * .5, val.values * 1.5,
                    color=l.get_color(), alpha=.4)

# define interactive legend

handles, labels = ax.get_legend_handles_labels() # return lines and labels
interactive_legend = plugins.InteractiveLegendPlugin(zip(handles,
                                                         ax.collections),
                                                     labels,
                                                     alpha_unsel=0.5,
                                                     alpha_over=1.5, 
                                                     start_visible=True)
plugins.connect(fig, interactive_legend)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Interactive legend', size=20)

mpld3.show()

https://mpld3.github.io/quickstart.html




回答3:


You can also use Plotly for that. This provides more interactive graphs. Also you can write the generated data in HTML files, apply bootstrap styling.

Check out this tutorial on their website.




回答4:


You may like to save the graph into specific location and write script to read the image file lets say pic.png into HTML. For taking input, you may create a Tabular structure of data and after each input, save the data to a file, lets say file.csv and read it in Python and keep adding values from input.

import matplotlib.pyplot as plt
df.hist()
plt.savefig('path/to/pic.png')

Now create HTML code to read that image file and output it as you want. I hope this helps.



来源:https://stackoverflow.com/questions/49015957/how-to-get-python-graph-output-into-html-webpage-directly

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