如何直接将python图形输出到html网页 [英] How to get python graph output into html webpage directly
问题描述
我正在使用不同的库(例如pandas和numpy)来生成数据框,最终生成图形.
I am using different libraries like pandas and numpy for generating a dataframe, which eventually generate a graph.
现在,我需要将此图显示为HTML格式的简单网页.
Now, I need to show this graph into a simple webpage which is in HTML.
注意:我也愿意在HTML页面中从用户那里接受2-3个输入,然后将该数据传递给我的python文件.然后,python文件根据给定的数据(来自HTML页面)生成一个图形,我需要将此图形传递给HTML页面.
df[[main_data]].plot()
在这里,main_data是变量,其值来自HTML页面.我在SPYDER中做python代码.我没有使用任何框架.
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.
推荐答案
这在某种程度上取决于您将图形显示为html的意思.我可以看到几种方法,第一种也是最简单的方法是将图形另存为png,然后在html中提供文件的路径:
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代码:
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'>
第二种方法是将图形编码为base64.这具有可移植性的优点,以及产生非常大的笨拙的html文件的缺点.我不是网络程序员,因此可能还有其他一些我不知道的注意事项
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
传递到您的html文件中,或者您可以使用jinja2或任何您使用的文件注入它.这是关于在HTML https://stackoverflow.com/a/8499716/3639023 中查看base64并将图像编码为base64 如何将PIL Image.image对象转换为base64字符串?
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?
这篇关于如何直接将python图形输出到html网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!