輸出與分享
Plotly 圖表可以輸出成三種形式:互動式 HTML 檔(write_html,任何瀏覽器開啟都能縮放、懸停)、靜態圖片(write_image,PNG/JPEG/SVG/PDF,放進簡報或論文),以及 JSON(write_json,保存圖表定義、給前端或 Dash 使用)。需要讓使用者自己切換篩選條件時,再把圖表放進 Dash 網頁應用程式。
互動式 HTML:write_html
import plotly.express as px
fig = px.scatter(px.data.iris(), x="sepal_width", y="sepal_length", color="species")
fig.write_html("iris.html")
預設會把整個 plotly.js(約 4–5 MB)包進 HTML,離線也能開。檔案大小與用途的取捨:
| 參數 | 效果 |
|---|---|
include_plotlyjs=True(預設) |
單一檔案、可離線,但較大 |
include_plotlyjs="cdn" |
從 CDN 載入 plotly.js,檔案只有幾十 KB,需要網路 |
full_html=False |
只輸出 <div>,方便嵌入既有網頁 |
config={"displaylogo": False} |
隱藏工具列上的 Plotly 標誌 |
auto_open=True |
存檔後自動用瀏覽器開啟 |
本站各頁嵌入的互動圖表,就是用 include_plotlyjs="cdn" 輸出的 HTML 檔,再以 <iframe> 放進頁面。
取得 HTML 字串而不存檔:html = fig.to_html(include_plotlyjs="cdn", full_html=False),可以直接放進 Flask、Django 範本或 Email。
靜態圖片:write_image
輸出靜態圖片需要另外安裝 Kaleido:
fig.write_image("iris.png", width=1000, height=600, scale=2) # scale=2 輸出高解析度
fig.write_image("iris.svg") # 向量圖,適合論文
fig.write_image("iris.pdf")
| 參數 | 說明 |
|---|---|
副檔名或 format |
png、jpg、webp、svg、pdf |
width、height |
輸出尺寸(像素);未指定時用 fig.layout 的設定,再沒有則 700×500 |
scale |
放大倍率,scale=2 相當於 2 倍解析度 |
Plotly 7 與 Kaleido v1
Plotly 7 只支援 Kaleido v1 以上,並移除了舊的 Orca 引擎與 engine 參數。Kaleido v1 使用電腦上的 Chrome/Chromium 繪圖;如果沒有安裝 Chrome,可以執行 plotly_get_chrome(命令列)或在 Python 中呼叫 plotly.io.get_chrome() 自動下載。
一次輸出多張圖時,用 plotly.io.write_images 會比迴圈呼叫 write_image 快很多:
import plotly.io as pio
# fig1、fig2、fig3 是已經建立好的 Figure
pio.write_images(fig=[fig1, fig2, fig3], file=["a.png", "b.png", "c.png"])
JSON:write_json 與 read_json
fig.write_json("iris.json")
import plotly.io as pio
fig2 = pio.read_json("iris.json") # 讀回 Figure,可以繼續修改
JSON 保存的是完整的圖表定義(資料、樣式),適合存檔、版本控制,或交給前端的 plotly.js 直接繪製。
放進 Dash 網頁應用程式
Dash 是 Plotly 官方的 Python 網頁框架,可以把 Plotly Express 圖表加上下拉選單、滑桿等元件,做成互動儀表板,而不需要寫 JavaScript:
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
df = px.data.gapminder()
app = Dash()
app.layout = html.Div([
html.H2("各洲平均壽命"),
dcc.Dropdown(sorted(df["continent"].unique()), "Asia", id="continent"),
dcc.Graph(id="graph"),
])
@app.callback(Output("graph", "figure"), Input("continent", "value"))
def update(continent):
d = df[df["continent"] == continent]
return px.line(d, x="year", y="lifeExp", color="country")
if __name__ == "__main__":
app.run(debug=True)
執行後瀏覽器開啟 http://127.0.0.1:8050,選擇不同洲別,圖表會即時更新。Dash 的入門影片見 官方影音。
其他分享方式
- Jupyter Notebook/Colab:圖表會保存在 Notebook 輸出中;上傳到 GitHub 時,GitHub 預覽不會執行 JavaScript,看不到互動圖,可改用 nbviewer 分享。
- Streamlit:
st.plotly_chart(fig)直接顯示 Plotly 圖。 - 靜態網站:把
write_html的檔案放進網站,用<iframe>嵌入(本站的做法)。
推薦影音
Introduction to Dash Plotly for building Python Data Apps(Plotly 官方頻道)
簡述:Plotly 官方的 Dash 入門教學,說明 Dash 應用程式結構、版面(layout)、callback 裝飾器與函式,最後示範把機器學習模型放進 Dash。對應本頁「放進 Dash 網頁應用程式」一節,原始碼在 Plotly 的 GitHub。