1. 程式人生 > >python 實現將 pandas 資料和 matplotlib 繪圖嵌入 html 檔案

python 實現將 pandas 資料和 matplotlib 繪圖嵌入 html 檔案

python 實現將 pandas 資料和 matplotlib 繪圖嵌入 html 檔案

實現用 python 將 pandas 的 DataFrame 資料以及 matplotlib 繪圖的影象儲存為 HTML 檔案

實現原理

  1. python 的 lxml 庫的 etree 模組可以實現解析 HTML 程式碼並寫入 html 檔案。如下所示:
from lxml import etree
root = """
<title>lxml example</title>
<h1>Hello lxml!</h1>
"""
html = etree.HTML(root) tree = etree.ElementTree(html) tree.write('hellolxml.html')
  1. pandas 的 DataFrame 資料,可直接呼叫 df.to_html() 函式將 DataFrame 資料轉為 HTML 程式碼字串。
  2. 從 HTML 檔案中可以發現,內嵌的圖片是以 base64 程式碼的形式嵌入的。具體形式為 <img src="data:image/png;base64,iVBORw...。後面的 iVBORw…即為影象的 Base64 編碼資訊。故而只需將影象轉為 base64 程式碼即可將影象嵌入 HTML 程式碼字串中。python 的 base64 模組可以實現將二進位制檔案轉為 base64 編碼,而 matplotlib 的
    pyplot.savefig()
    函式可以將繪圖視窗儲存為二進位制檔案格式。

python 程式碼實現

最終便可使用 python 實現將將 pandas 的 DataFrame 資料以及 matplotlib 繪圖的影象儲存為 HTML 檔案,程式碼如下。(以下程式碼基於 python 3.6 實現的。)

# 匯入所需模組
import pandas as pd
import matplotlib.pyplot as plt
from io import BytesIO
from lxml import etree
import base64
import urllib


# 獲取資料集,用 urllib 庫下載 iris 資料集作為示例
url = "http://aima.cs.berkeley.edu/data/iris.csv" setl = urllib.request.Request(url) iris_p = urllib.request.urlopen(setl) iris = pd.read_csv(iris_p, sep=',',decimal='.',header=None, names=['Sepal_Length','Sepal_Width','Petal_Length','Petal_Width','Species']) # pandas 的 DataFrame 資料直接裝換為 html 程式碼字串 iris_des = """<h1>Iris Describe Stastic</h1>"""+iris.describe().T.to_html() # matplotlib 任意繪製一張圖 fig,axes = plt.subplots(1,4,sharey = True) for n in range(4): axes[n].hist( iris.iloc[:,n],bins = 15,color = 'b',alpha = 0.5,rwidth= 0.8 ) axes[n].set_xlabel(iris.columns[n]) plt.subplots_adjust(wspace = 0) # figure 儲存為二進位制檔案 buffer = BytesIO() plt.savefig(buffer) plot_data = buffer.getvalue() # 影象資料轉化為 HTML 格式 imb = base64.b64encode(plot_data) #imb = plot_data.encode('base64') # 對於 Python 2.7可用 ims = imb.decode() imd = "data:image/png;base64,"+ims iris_im = """<h1>Iris Figure</h1> """ + """<img src="%s">""" % imd root = "<title>Iris Dataset</title>" root = root + iris_des + iris_im #將多個 html 格式的字串連線起來 # lxml 庫的 etree 解析字串為 html 程式碼,並寫入檔案 html = etree.HTML(root) tree = etree.ElementTree(html) tree.write('iris.html') # 最後使用預設瀏覽器開啟 html 檔案 import webbrowser webbrowser.open('iris.html',new = 1)