2026年4月30日 星期四

Python 學習筆記 : 用 plotly 繪製互動式圖表 (三)

本篇旨在測試 Plotly 的圖表匯出功能. 


Plotly 支援多種檔案類型匯出, 可呼叫下表中 Figure 物件的方法匯出 :


Figure 物件的檔案匯出方法 說明
fig.write_image(file, **kwargs) 匯出為靜態圖片(PNG、JPEG、SVG、PDF 等),需安裝 kaleido
fig.write_html(file, **kwargs) 匯出為互動式 HTML 檔,可直接用瀏覽器開啟
fig.to_html(full_html=True, include_plotlyjs='cdn') 將圖表轉為 HTML 字串(用於網頁內嵌或 API 回傳)
fig.to_json() 將圖表轉為 JSON 格式(適合儲存、API 傳遞、版本控管)
fig.write_json(file) 將圖表 JSON 結構直接寫入檔案
fig.to_dict() 將圖表轉為 Python 字典格式,可進一步程式操作


注意, fig.write_image() 方法須依賴 kaleido 模組, 這是 Plotly 官方推出的匯圖引擎模組, 用來將 Plotly 圖表儲存為靜態圖片.


1. 匯出圖檔 : 

呼叫 Figure 物件的 write_image() 方法可將繪製的圖表匯出成圖片檔 (支援 PNG, JPG, SVG, PDF 等檔案類型), 其參數結構如下 :

fig.write_image(
    file,             # 必填,檔案路徑字串或類似檔案的物件
    format=None,      # 圖片格式,如 'png'、'jpeg'、'svg'、'pdf',若省略會自動從副檔名判斷
    width=None,       # 圖片寬度(像素),預設為圖表原始寬度
    height=None,      # 圖片高度(像素),預設為圖表原始高度
    scale=1,          # 圖片縮放倍數(例如 2 表示解析度加倍)
    validate=True,    # 是否檢查圖表是否有效(預設 True)
    engine='kaleido'  # 使用的圖像引擎,預設為 'kaleido'
    )

不過使用此方法之前須先安裝 Plotly 的 kaleido 模組, 而且 plotly 也要提升至最新版 :

pip install kaleido   
pip install plotly -U

在前一篇測試中使用了 plotly.express 來繪製長條圖, 下列沿用此範例來匯出所繪製的圖檔 : 

# plotly_chart_export_1.py
import plotly.express as px
import pandas as pd
import os

# 1. 資料來源
data={
    '月份': ['一月', '二月', '三月', '四月', '五月'],
    '營收': [120000, 135000, 99000, 150000, 170000]    
    }

# 2. 建立 Figure 圖表物件
# 注意:這裡設定了 width 和 height,匯出圖片時會以此為基準
fig=px.bar(data, x='月份', y='營收', width=800, height=600, title="月營收統計圖")

# 3. 顯示圖表 (選用)
fig.show()

# 4. 匯出圖檔 
# 建立儲存目錄(選用,避免檔案雜亂)
if not os.path.exists("output"):
    os.mkdir("output")
# 匯出為 PNG
fig.write_image("output/revenue_report.png", scale=2)
# 匯出為 JPG
fig.write_image("output/revenue_report.jpg", scale=2)
print("圖檔已匯出至 output 資料夾中。")

執行結果除了 fig.show() 會開啟瀏覽器顯示長條圖外, 也會在目前工作目錄下建立 output 子目錄存放匯出的兩個圖檔 :

>>> %Run plotly_chart_export_1.py   
圖檔已匯出至 output 資料夾中。




2. 匯出網頁 : 

呼叫 fig.write_html() 可將繪製之圖表匯出為 HTML 檔, 若傳入 include_plotlyjs='cdn' 參數會使用 CDN 的 plotly 函式庫, 這樣匯出的 HTML 檔較小但須連網才能看到互動圖表; 否則會將 plotly 函式庫一同匯出, 檔案較大些 (約 4MB) 但不須連網, 離線開啟網頁即可看到互動圖表.

程式碼如下 : 

# plotly_chart_export_2.py
import plotly.express as px
import pandas as pd
import os

# 1. 資料來源
data={
    '月份': ['一月', '二月', '三月', '四月', '五月'],
    '營收': [120000, 135000, 99000, 150000, 170000]    
    }

# 2. 建立 Figure 圖表物件
fig=px.bar(data, x='月份', y='營收', width=800, height=600, title="月營收統計圖 (互動式 HTML)")

# 3. 建立儲存目錄
output_dir="output"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# --- 匯出 HTML  ---
# 方式 A:標準匯出 (將 Plotly.js 核心程式碼打包進去,檔案約 4 MB,可離線開啟)
fig.write_html(os.path.join(output_dir, "report_full.html"))

# 方式 B:輕量化匯出 (使用 CDN 連結,檔案僅約 50KB,開啟時需連網載入 JS)
fig.write_html(
    os.path.join(output_dir, "report_cdn.html"), 
    include_plotlyjs='cdn'
    )

print(f"✅ HTML 檔案已匯出至 {output_dir} 資料夾。")
print("- report_full.html (可離線檢視)")
print("- report_cdn.html (體積小,需連網)")

# 顯示圖表
fig.show()

執行結果如下 :

>>> %Run plotly_chart_export_2.py
✅ HTML 檔案已匯出至 output 資料夾。
- report_full.html (可離線檢視)
- report_cdn.html (體積小,需連網)

開啟 output 資料夾下的網頁檔即可看到長條圖 :




沒有留言 :