如何直接将python图形输出到html网页中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49015957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:57:36  来源:igfitidea点击:

How to get python graph output into html webpage directly

pythonhtmlpandasgraph

提问by Jay Desai

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

我使用不同的库,如 pandas 和 numpy 来生成数据框,最终生成一个图形。

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

现在,我需要将此图形显示到一个简单的 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.

注意:我也愿意在 HTML 页面中从用户那里获取 2-3 个输入,然后将该数据传递给我的 python 文件。之后,python 文件根据给定的数据(来自 HTML 页面)生成一个图形,我需要将此图形传递给一个 HTML 页面。

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.

这里,main_data 是变量,其值来自 HTML 页面。我正在 SPYDER 中执行 python 代码。而且我没有使用任何框架。

回答by johnchase

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:

这在某种程度上取决于您将图形显示为 html 的含义。我可以看到几种方法,第一个也是最简单的方法是将图形保存为 png,然后在 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:

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

第二种方法是将数字编码为 base64。这具有可移植的优点,但缺点是制作非常大的笨拙的 html 文件。我不是网络程序员,所以可能还有其他一些我不知道的警告

python:

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_htmlcan 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/3639023and encoding images as base64 How to convert PIL Image.image object to base64 string?

my_html可以传递给你的 html 文件,或者你可以用 jinja2 或任何你使用的东西注入它。这是关于在 html https://stackoverflow.com/a/8499716/3639023 中查看 base64并将图像编码为 base64如何将 PIL Image.image 对象转换为 base64 字符串的SO 帖子

回答by Noor Ameen

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

将 matplotlib 图表导出到 Web 浏览器的最佳方法是使用 mpld3 库。 这是示例。

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

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

回答by niranjan patidar

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

您也可以Plotly为此使用。这提供了更多interactive graphs。您也可以将生成的数据写入HTML files, apply bootstrap styling.

Check out this tutorial on their website.

在他们的网站上查看本教程

回答by Harry_pb

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

您可能希望将图形保存到特定位置并编写脚本来读取图像文件,例如pic.png进入HTML. 为了获取输入,您可以创建一个Tabular数据结构,并在每次输入后将数据保存到一个文件中,让我们说file.csv并读入它Python并继续从输入中添加值。

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.

现在创建 HTML 代码来读取该图像文件并根据需要输出它。我希望这有帮助。