如何直接将python图形输出到html网页
我使用不同的库,如pandas和numpy来生成数据帧,最终生成一个图形 现在,我需要将此图显示为一个简单的HTML网页 注意:我也愿意在HTML页面中接受用户的2-3个输入,然后将该数据传递给我的python文件。之后,python文件根据给定数据(来自HTML页面)生成一个图形,我需要将该图形传递到HTML页面。如何直接将python图形输出到html网页,python,html,pandas,graph,Python,Html,Pandas,Graph,我使用不同的库,如pandas和numpy来生成数据帧,最终生成一个图形 现在,我需要将此图显示为一个简单的HTML网页 注意:我也愿意在HTML页面中接受用户的2-3个输入,然后将该数据传递给我的python文件。之后,python文件根据给定数据(来自HTML页面)生成一个图形,我需要将该图形传递到HTML页面。 df[[main_data]].plot() import matplotlib.pyplot as plt import numpy as np import pandas a
df[[main_data]].plot()
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()
这里,main_数据是一个变量,其值来自HTML页面。我正在用SPYDER编写python代码我没有使用任何框架。您可能希望将图形保存到特定位置,并编写脚本来读取图像文件,比如说
pic.png
到HTML
。对于输入,您可以创建一个表格
数据结构,在每次输入后,将数据保存到一个文件中,比如说file.csv
,然后在Python
中读取,并不断从输入中添加值
df[[main_data]].plot()
import matplotlib.pyplot as plt
df.hist()
plt.savefig('path/to/pic.png')
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()
现在创建HTML代码来读取该图像文件并根据需要输出它。我希望这会有所帮助。这在某种程度上取决于您将图形显示为html的意思。我可以看到两种方法,第一种也是最简单的方法是将图形保存为png,然后在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:
第二种方法是将图形编码为base64。这样做的优点是可移植,缺点是生成非常大且难以处理的html文件。我不是一个网络程序员,所以可能还有其他我不知道的警告
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'))
导入io
导入base64
def fig_至_base64(图)
img=io.BytesIO()
图savefig(img,格式为png),
bbox_英寸(紧)
img.seek(0)
返回base64.b64encode(img.getvalue())
编码=图u至图u base64(图)
my_html=''.format(编码的.decode('utf-8'))
my_html
可以传递到您的html文件中,或者您可以使用jinja2或您使用的任何东西将其注入。下面是一篇关于在html中查看base64并将图像编码为base64的文章。将matplotlib图表导出到web浏览器的最佳方法是使用mpld3库。
以下是示例。
df[[main_data]].plot()
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()
您也可以使用
Plotly
。这提供了更多的交互式图形。
您还可以将生成的数据写入HTML文件,应用引导样式设置
查看。我还想尝试一下graph.js库。您可以使用请求库(或实现Django或Flask等框架)将数据从python传递到HTML