使用 plotly 圖形庫的範例#

Sphinx-Gallery 支援使用 plotly 函式庫製作的範例。 Sphinx-Gallery 能夠擷取 plotly 圖形物件的 _repr_html_ (請參閱 控制擷取的輸出)。 要顯示圖形,程式碼區塊中的最後一行應該是 plotly 圖形物件。

為了使用 plotly,專案的 conf.py 應該包含以下幾行,以選擇適當的 plotly 渲染器

import plotly.io as pio
pio.renderers.default = 'sphinx_gallery'

可選:plotly 的 sphinx_gallery 渲染器不會產生 png 縮圖。 若要使用 png 縮圖,您可以改用 sphinx_gallery_png 渲染器,並將 plotly.io._sg_scraper.plotly_sg_scraper 加入 圖像擷取器 的清單中。 擷取器需要您安裝 orca 套件

本教學提供一些 plotly 圖形的範例,從其高階 API plotly express 開始。

import numpy as np
import plotly.express as px

df = px.data.tips()
fig = px.bar(
    df,
    x="sex",
    y="total_bill",
    facet_col="day",
    color="smoker",
    barmode="group",
    template="presentation+plotly",
)
fig.update_layout(height=400)
fig


除了傳統的散佈圖或長條圖之外,plotly 還提供了多種 trace,例如以下範例中的旭日層級追蹤。 plotly 是一個互動式函式庫:點擊其中一個大陸即可獲得更詳細的鑽取檢視。

df = px.data.gapminder().query("year == 2007")
fig = px.sunburst(
    df,
    path=["continent", "country"],
    values="pop",
    color="lifeExp",
    hover_data=["iso_alpha"],
    color_continuous_scale="RdBu",
    color_continuous_midpoint=np.average(df["lifeExp"], weights=df["pop"]),
)
fig.update_layout(title_text="Life expectancy of countries and continents")
fig


雖然 plotly express 通常是 plotly 函式庫的高階入口點,但可以使用低階 graph_objects 命令式 API 製作混合不同類型 trace 的複雜圖形。

import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(rows=1, cols=2, specs=[[{}, {"type": "domain"}]])
fig.add_trace(go.Bar(x=[2018, 2019, 2020], y=[3, 2, 5], showlegend=False), 1, 1)
fig.add_trace(go.Pie(labels=["A", "B", "C"], values=[1, 3, 6]), 1, 2)
fig.update_layout(height=400, template="presentation", yaxis_title_text="revenue")
fig

# sphinx_gallery_thumbnail_path = '_static/plotly_logo.png'


腳本的總執行時間: (0 分鐘 1.260 秒)

預估的記憶體使用量: 188 MB

由 Sphinx-Gallery 產生的展示