R

ReflexKR

Reflex公式ドキュメント

コンポーネント工房:Reflexライブラリ100

·

講座の概要

レイアウト

·

Box

·

Flex

·

Stack

·

Grid

·

Container

·

Section

·

Center

·

Spacer

·

Separator

·

Card

·

Inset

·

Aspect Ratio

·

Fragment

タイポグラフィ

·

Text

·

Heading

·

Link

·

Code

·

Markdown

·

Blockquote

·

Quote

·

Strong

·

Em

·

Kbd

フォーム

·

Button

·

Input

·

Text Area

·

Checkbox

·

Switch

·

Radio Group

·

Select

·

Slider

·

Form

·

Upload

データ表示

·

Badge

·

Avatar

·

Icon

·

Callout

·

List

·

Data List

·

Code Block

·

Progress

·

Spinner

·

Scroll Area

·

Moment

開閉と切り替え

·

Tabs

·

Accordion

·

Segmented Control

オーバーレイ

·

Tooltip

·

Popover

·

Hover Card

·

Dialog

·

Alert Dialog

·

Drawer

·

Dropdown Menu

·

Context Menu

·

Toast

動的レンダリング

·

Cond

·

Match

·

Foreach

·

Auto Scroll

メディア

·

Image

·

Audio

·

Video

表とデータグリッド

·

Table

·

Data Table

·

Data Editor

チャート

·

Area Chart

·

Bar Chart

·

Line Chart

·

Composed Chart

·

Pie Chart

·

Radar Chart

·

Radial Bar Chart

·

Scatter Chart

·

Funnel Chart

·

Treemap

·

Sankey Chart

·

Error Bar

チャートの部品

·

Axis

·

Cartesian Grid

·

Chart Tooltip

·

Legend

·

Label

·

Reference

·

Brush

ほかのチャートライブラリ

·

Plotly

·

Pyplot

HTML要素

·

HTML

·

HTML Text

·

HTML Layout

·

HTML Forms

·

HTML Media

·

HTML Tables

·

SVG

そのほかの道具

·

Theme

·

Skeleton

·

Clipboard

·

Html Embed

·

Script

·

Memo

コンポーネント工房:Reflexライブラリ100
ほかのチャートライブラリ

Plotly

工房の注文書

製品別の1年間の売上を拡大・縮小しながら見られるインタラクティブなチャートにして、製品を選ぶとチャートが切り替わるようにしてください。

Plotly は、拡大、移動、マウスオーバーができるインタラクティブなチャートを作る Python ライブラリです。rx.plotly は Plotly の Figure をそのまま受け取ってブラウザに描画します。折れ線・棒のような基本のチャートはもちろん、ヒートマップ・3D・金融チャートまで JavaScript なしで使えます。

普段のスクリプトのように fig.show() を呼ぶのではなく、UI のコードで rx.plotly(data=fig) に渡します。必要なパッケージは plotly で、この講座では plotly.graph_objects(go)で図を作ります。

import plotly.graph_objects as go

plotly_years = [1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992, 1997, 2002, 2007]
plotly_canada = [68.75, 69.96, 71.3, 72.13, 72.88, 74.21, 75.76, 76.86, 77.95, 78.61, 79.77, 80.65]

plotly_line_fig = go.Figure(go.Scatter(x=plotly_years, y=plotly_canada, mode="lines", name="Canada"))
plotly_line_fig.update_layout(title="Life expectancy in Canada")


rx.plotly(data=plotly_line_fig, width="100%")

公式ドキュメントの例の多くは plotly.express(px)を使っています。px には pandas が必要なので、このページでは同じ図を go で作り、データは Python のリストで書きます。px で作った図も Figure なので、rx.plotly に渡す方法は同じです。

プロパティを変えてみる

layout に dict を渡すと、図のレイアウトの上に上書きされます。同じ図のまま、タイトル、高さ、背景を画面側でだけ変えたいときに便利です。下の実習台といくつかの例は、上の plotly_line_fig をそのまま使います。

プロパティを変えてみる

title

height

400

showlegend

plot_bgcolor

locale

rx.plotly(
    data=plotly_line_fig,
    layout={"title": {"text": "Life expectancy"}, "height": 400, "showlegend": False, "plot_bgcolor": "rgba(0,0,0,0)"},
    locale="en",
    width="100%",
)
layout は図のレイアウトに上書きされ、locale は数値の形式と右上のツールバーの案内文字を変えます。
プロパティ値既定値用途
datago.Figure またはその dict-描画する図。State の値も使える
layoutdict-図のレイアウトに上書きする値
templatePlotly の Templateライトモードは plotly、ダークモードは plotly_dark全体の色・フォントのテーマ
configdict-ツールバー、スクロールでの拡大などの Plotly の設定
locale"de" "ko" …-数値・日付の形式とツールバーの文字の言語
use_resize_handlerTrue / FalseTrueウィンドウのサイズが変わったら合わせ直す
on_click · on_hover · on_unhover · on_selected · on_selectingイベント-点のリスト(list[dict])を渡す
on_relayout · on_double_click · on_deselect · on_after_plot などイベント-拡大・移動、ダブルクリック、選択解除、再描画のあと(引数なし)

template を指定しなければ、Reflex がライトモードとダークモードに合わせてテーマを切り替えてくれます。Reflex 0.10 の rx.plotly には、公式ドキュメントの表にない on_click と on_double_click もあります。

いろいろなチャート

公式ドキュメントの Plotly Express の例を go に書き換えたものです。どんな図でも rx.plotly(data=図) で渡すのは同じです。データは例のために作った値です。

棒チャート

go.Bar を複数入れ、barmode="group" で横に並べます。px.bar(..., color="country") に相当します。

import plotly.graph_objects as go

plotly_bar_fig = go.Figure([
    go.Bar(name="Chairs", x=["Q1", "Q2", "Q3", "Q4"], y=[120, 150, 170, 210]),
    go.Bar(name="Tables", x=["Q1", "Q2", "Q3", "Q4"], y=[80, 95, 130, 120]),
])
plotly_bar_fig.update_layout(barmode="group", title="Orders by quarter")


rx.plotly(data=plotly_bar_fig, width="100%")

散布図

go.Scatter に mode="markers" を指定すると点だけを打ちます。グループごとに trace を1つずつ作ると、色と凡例が別々に付きます。

import random
import plotly.graph_objects as go

plotly_scatter_rng = random.Random(7)
plotly_scatter_fig = go.Figure([
    go.Scatter(
        x=[plotly_scatter_rng.gauss(cx, 0.3) for _ in range(30)],
        y=[plotly_scatter_rng.gauss(cy, 0.4) for _ in range(30)],
        mode="markers",
        name=name,
    )
    for name, cx, cy in [("A", 3.4, 5.0), ("B", 2.8, 5.9), ("C", 3.0, 6.6)]
])
plotly_scatter_fig.update_layout(title="Sample clusters", xaxis_title="width", yaxis_title="length")


rx.plotly(data=plotly_scatter_fig, width="100%")

円グラフ

go.Pie に名前(labels)と値(values)を渡します。割合は Plotly が計算します。

import plotly.graph_objects as go

plotly_pie_fig = go.Figure(go.Pie(labels=["Thur", "Fri", "Sat", "Sun"], values=[171.83, 51.96, 260.40, 247.39]))
plotly_pie_fig.update_layout(title="Tips by day")


rx.plotly(data=plotly_pie_fig, width="100%")

ヒートマップ

go.Histogram2d は、2つの値の組が多く集まったマスほど濃く塗ります(px.density_heatmap)。すでに計算済みの表があるなら go.Heatmap(z=...) を使います。

import random
import plotly.graph_objects as go

plotly_heat_rng = random.Random(3)
plotly_bills = [plotly_heat_rng.gauss(20, 8) for _ in range(300)]
plotly_tips = [b * 0.15 + plotly_heat_rng.gauss(0, 0.8) for b in plotly_bills]

plotly_heatmap_fig = go.Figure(go.Histogram2d(x=plotly_bills, y=plotly_tips, nbinsx=20, nbinsy=15))
plotly_heatmap_fig.update_layout(title="Bill vs tip density heatmap")


rx.plotly(data=plotly_heatmap_fig, width="100%")

ヒストグラム

go.Histogram は値を区間に分けて個数を数えます。nbinsx は区間数の上限です。

import random
import plotly.graph_objects as go

plotly_hist_rng = random.Random(5)
plotly_hist_fig = go.Figure(go.Histogram(x=[plotly_hist_rng.gauss(20, 8) for _ in range(250)], nbinsx=20))
plotly_hist_fig.update_layout(title="Distribution of total bills")


rx.plotly(data=plotly_hist_fig, width="100%")

箱ひげ図

go.Box は中央値、四分位、外れ値を1つの箱で示します。グループごとに trace を1つずつ置きます。

import random
import plotly.graph_objects as go

plotly_box_rng = random.Random(11)
plotly_box_fig = go.Figure([
    go.Box(y=[plotly_box_rng.gauss(mean, 6) for _ in range(40)], name=day)
    for day, mean in [("Thur", 17), ("Fri", 17), ("Sat", 20), ("Sun", 21)]
])
plotly_box_fig.update_layout(title="Total bill by day")


rx.plotly(data=plotly_box_fig, width="100%")

バブルチャート

散布図の点の大きさ(marker.size)で3つ目の値を表します。x 軸を type="log" に変えると px.scatter(..., log_x=True) と同じになります。

import plotly.graph_objects as go

plotly_bubble_fig = go.Figure(go.Scatter(
    x=[800, 2500, 6000, 15000, 32000, 45000],
    y=[52, 61, 68, 74, 79, 82],
    text=["A", "B", "C", "D", "E", "F"],
    mode="markers",
    marker={"size": [20, 45, 30, 60, 25, 40], "color": [1, 2, 3, 4, 5, 6], "colorscale": "Viridis"},
))
plotly_bubble_fig.update_xaxes(type="log", title="income")
plotly_bubble_fig.update_layout(title="Income vs life expectancy", yaxis_title="years")


rx.plotly(data=plotly_bubble_fig, width="100%")

ガントチャート

スケジュール表は横棒(orientation="h")で描きます。棒の始まりは base、長さはミリ秒単位の期間で、x 軸を日付の軸にします。px.timeline が内部でしていることと同じです。y 軸を反転して、上から下へ読めるようにします。

from datetime import date
import plotly.graph_objects as go

plotly_jobs = [("Job A", "2009-01-01", "2009-02-28"), ("Job B", "2009-03-05", "2009-04-15"), ("Job C", "2009-02-20", "2009-05-30")]
plotly_gantt_fig = go.Figure(go.Bar(
    y=[job for job, start, end in plotly_jobs],
    base=[start for job, start, end in plotly_jobs],
    x=[(date.fromisoformat(end) - date.fromisoformat(start)).days * 86_400_000 for job, start, end in plotly_jobs],
    orientation="h",
))
plotly_gantt_fig.update_xaxes(type="date")
plotly_gantt_fig.update_yaxes(autorange="reversed")


rx.plotly(data=plotly_gantt_fig, width="100%")

サンバーストチャート

階層データを、中央の根から外側の輪へと広げます。labels と parents で親子関係を書きます。

import plotly.graph_objects as go

plotly_sunburst_fig = go.Figure(go.Sunburst(
    labels=["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],
    parents=["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve"],
    values=[10, 14, 12, 10, 2, 6, 6, 4, 4],
))


rx.plotly(data=plotly_sunburst_fig, width="100%")

ファネルチャート

訪問から購入まで、段階ごとにどれだけ減るかを示します。どの段階で多く離脱するかを探すときに使います。

import plotly.graph_objects as go

plotly_funnel_fig = go.Figure(go.Funnel(
    x=[39, 27.4, 20.6, 11, 2],
    y=["Website visit", "Downloads", "Potential customers", "Requested price", "Invoice sent"],
))


rx.plotly(data=plotly_funnel_fig, width="100%")

言語と数値の形式:locale

locale は、数値・日付の形式とツールバーの案内文字をその言語に変えます。下はドイツ語です。config を一緒に指定してもよく、両方あるときは locale の値が最後に適用されます。

rx.plotly(data=plotly_line_fig, locale="de", width="100%")

3D 曲面

go.Surface に高さの値の2次元リスト(z)を渡すと曲面になります。公式ドキュメントは CSV ファイルの山の標高データを読み込みますが、ここでは数式で作った値を使います。ドラッグして回転できます。

import math
import plotly.graph_objects as go

plotly_surface_z = [[60 + 40 * math.sin(x / 4) * math.cos(y / 5) + y for x in range(30)] for y in range(30)]

plotly_surface_fig = go.Figure(data=[go.Surface(z=plotly_surface_z)])
plotly_surface_fig.update_traces(contours_z=dict(show=True, usecolormap=True, highlightcolor="limegreen", project_z=True))
plotly_surface_fig.update_layout(scene_camera_eye=dict(x=1.87, y=0.88, z=-0.64), margin=dict(l=65, r=50, b=65, t=90))


rx.plotly(data=plotly_surface_fig, width="100%")

金融チャート

ローソク足

日付ごとに始値・高値・安値・終値を1本のろうそくで描きます。実体は始値と終値の間、ひげは安値と高値の間です。

import plotly.graph_objects as go

plotly_candle_fig = go.Figure(go.Candlestick(
    x=["2024-01-02", "2024-01-03", "2024-01-04", "2024-01-05", "2024-01-08", "2024-01-09"],
    open=[187.15, 184.22, 182.15, 181.99, 182.09, 183.92],
    high=[188.44, 185.88, 183.09, 182.76, 185.60, 185.15],
    low=[183.89, 183.43, 180.88, 180.17, 181.50, 182.73],
    close=[185.64, 184.25, 181.91, 181.18, 185.56, 185.14],
))
plotly_candle_fig.update_layout(title=dict(text="Stock price"), yaxis=dict(title=dict(text="USD")))


rx.plotly(data=plotly_candle_fig, width="100%")

ウォーターフォールチャート

最初の値が、加算・減算の項目を経てどう変わるかを示します。measure で、各項目が変化量("relative")か合計("total")かを決めます。

import plotly.graph_objects as go

plotly_waterfall_fig = go.Figure(go.Waterfall(
    name="2018",
    orientation="v",
    measure=["relative", "relative", "total", "relative", "relative", "total"],
    x=["Sales", "Consulting", "Net revenue", "Purchases", "Other expenses", "Profit before tax"],
    textposition="outside",
    text=["+60", "+80", "", "-40", "-20", "Total"],
    y=[60, 80, 0, -40, -20, 0],
    connector={"line": {"color": "rgb(63, 63, 63)"}},
))
plotly_waterfall_fig.update_layout(title="Profit and loss statement 2018", showlegend=True)


rx.plotly(data=plotly_waterfall_fig, width="100%")

ブレットチャート

メーターの代わりに使う小さな棒です。go.Indicator に gauge.shape="bullet" を指定し、実績の棒・区間(steps)・目標線(threshold)を1行に収めます。

import plotly.graph_objects as go

plotly_bullet_fig = go.Figure(go.Indicator(
    mode="number+gauge+delta",
    value=180,
    delta={"reference": 200},
    domain={"x": [0.25, 1], "y": [0.4, 0.6]},
    title={"text": "Revenue"},
    gauge={
        "shape": "bullet",
        "axis": {"range": [None, 300]},
        "threshold": {"line": {"color": "black", "width": 2}, "thickness": 0.75, "value": 170},
        "steps": [{"range": [0, 150], "color": "gray"}, {"range": [150, 250], "color": "lightgray"}],
        "bar": {"color": "black"},
    },
))
plotly_bullet_fig.update_layout(height=250)


rx.plotly(data=plotly_bullet_fig, width="100%")

統計チャート:連続した誤差帯

誤差を棒ではなく、線の周りの薄い帯で示します。上側の境界を順方向に、下側の境界を逆方向につないで一周する線を作り、fill="toself" で中を塗ります。

import plotly.graph_objects as go

plotly_band_x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
plotly_band_y = [1, 2, 7, 4, 5, 6, 7, 8, 9, 10]
plotly_band_upper = [2, 3, 8, 5, 6, 7, 8, 9, 10, 11]
plotly_band_lower = [0, 1, 5, 3, 4, 5, 6, 7, 8, 9]

plotly_band_fig = go.Figure([
    go.Scatter(x=plotly_band_x, y=plotly_band_y, line=dict(color="rgb(0,100,80)"), mode="lines"),
    go.Scatter(
        x=plotly_band_x + plotly_band_x[::-1],
        y=plotly_band_upper + plotly_band_lower[::-1],
        fill="toself",
        fillcolor="rgba(0,100,80,0.2)",
        line=dict(color="rgba(255,255,255,0)"),
        hoverinfo="skip",
        showlegend=False,
    ),
])


rx.plotly(data=plotly_band_fig, width="100%")

地図(コードのみ)

Plotly の地図は、描画するときに外部サーバーから地図データを取得します。輪郭の地図(Scattergeo、Choropleth)は Plotly CDN の地形データを、タイル地図(Scattermap)は地図タイルサーバーを使います。この講座では外部リソースを使わないため、コードだけを示します。アプリではそのまま動作します。

輪郭の地図

輪郭の地図の設定は図の layout.geo にあり、update_geos で湖・川などの表示を変えます。

import plotly.graph_objects as go

geo_fig = go.Figure(go.Scattergeo())
geo_fig.update_geos(
    visible=False,
    resolution=50,
    showlakes=True,
    lakecolor="Blue",
    showrivers=True,
    rivercolor="Blue",
)
geo_fig.update_layout(height=300, margin={"r": 0, "t": 0, "l": 0, "b": 0})


def geo_map_chart():
    return rx.plotly(data=geo_fig, width="100%")

散布図の地図

タイル地図の上に点を打ちます。公式ドキュメントは px.scatter_map を使い、go では go.Scattermap です。地図の見た目は layout.map で決めます。

import plotly.graph_objects as go

map_fig = go.Figure(go.Scattermap(
    lat=[37.57, 35.18, 35.87],
    lon=[126.98, 129.08, 128.60],
    text=["Seoul", "Busan", "Daegu"],
    mode="markers",
    marker={"size": [18, 12, 10]},
))
map_fig.update_layout(
    map={"style": "open-street-map", "center": {"lat": 36.4, "lon": 127.8}, "zoom": 5},
    margin={"r": 0, "t": 0, "l": 0, "b": 0},
)


def scatter_map_chart():
    return rx.plotly(data=map_fig, width="100%")

表とフロー図

表

go.Table は header に列名を、cells に列ごとの値のリストを受け取ります。スクロールや列の並べ替えができます。

import plotly.graph_objects as go

plotly_table_fig = go.Figure(go.Table(
    header=dict(values=["A Scores", "B Scores"]),
    cells=dict(values=[[100, 90, 80, 90], [95, 85, 75, 95]]),
))


rx.plotly(data=plotly_table_fig, width="100%")

サンキーダイアグラム

流れの量を帯の太さで示します。node.label にノード名を書き、link で source→target をノードの番号でつなぎます。

import plotly.graph_objects as go

plotly_sankey_fig = go.Figure(go.Sankey(
    node=dict(pad=15, thickness=20, line=dict(color="black", width=0.5), label=["A1", "A2", "B1", "B2", "C1", "C2"], color="blue"),
    link=dict(source=[0, 1, 0, 2, 3, 3], target=[2, 3, 3, 4, 4, 5], value=[8, 4, 2, 8, 4, 2]),
))
plotly_sankey_fig.update_layout(title_text="Basic Sankey Diagram", font_size=10)


rx.plotly(data=plotly_sankey_fig, width="100%")

3D チャート

3D 散布図

go.Scatter3d は3つの値の関係を空間に打ちます(px.scatter_3d)。

import random
import plotly.graph_objects as go

plotly_s3d_rng = random.Random(2)
plotly_s3d_fig = go.Figure([
    go.Scatter3d(
        x=[plotly_s3d_rng.gauss(cx, 0.4) for _ in range(30)],
        y=[plotly_s3d_rng.gauss(cy, 0.3) for _ in range(30)],
        z=[plotly_s3d_rng.gauss(cz, 0.3) for _ in range(30)],
        mode="markers",
        marker={"size": 4},
        name=name,
    )
    for name, cx, cy, cz in [("A", 5.0, 3.4, 0.2), ("B", 5.9, 2.8, 1.3), ("C", 6.6, 3.0, 2.0)]
])


rx.plotly(data=plotly_s3d_fig, width="100%")

3D の軸

3D の図では scene の中に軸があります。scene.xaxis のように軸ごとに nticks(目盛りの数)と range(範囲)を決めます。公式ドキュメントは numpy の乱数を使いますが、ここでは random で同じことをします。

import random
import plotly.graph_objects as go

plotly_mesh_rng = random.Random(1)
plotly_mesh_fig = go.Figure(go.Mesh3d(
    x=[70 * plotly_mesh_rng.gauss(0, 1) for _ in range(70)],
    y=[55 * plotly_mesh_rng.gauss(0, 1) for _ in range(70)],
    z=[40 * plotly_mesh_rng.gauss(0, 1) for _ in range(70)],
    opacity=0.5,
    color="rgba(244,22,100,0.6)",
))
plotly_mesh_fig.update_layout(
    scene=dict(
        xaxis=dict(nticks=4, range=[-100, 100]),
        yaxis=dict(nticks=4, range=[-50, 100]),
        zaxis=dict(nticks=4, range=[-100, 100]),
    ),
    margin=dict(r=20, l=10, b=10, t=10),
)


rx.plotly(data=plotly_mesh_fig, width="100%")

State で図を切り替える

図を State の値に置くと、実行中に変えられます。公式ドキュメントは go.Figure を State 変数に入れますが、ここでは State に数値だけを置き、@rx.var の計算値が図を作ります。スライダーを動かすと計算値が作り直され、チャートが変わります。

import math
import plotly.graph_objects as go


class PlotlyWaveState(rx.State):
    cycles: int = 2

    @rx.event
    def set_cycles(self, value: list[float]):
        self.cycles = int(value[0])

    @rx.var
    def figure(self) -> go.Figure:
        xs = [i / 50 for i in range(101)]
        fig = go.Figure(go.Scatter(x=xs, y=[math.sin(2 * math.pi * self.cycles * x) for x in xs], mode="lines"))
        fig.update_layout(title=f"{self.cycles} cycles", height=300)
        return fig


rx.vstack(
    rx.slider(value=[PlotlyWaveState.cycles], min=1, max=8, step=1, on_change=PlotlyWaveState.set_cycles, width="240px"),
    rx.plotly(data=PlotlyWaveState.figure, width="100%"),
    width="100%",
)

クリックした点を受け取る

on_click、on_hover、on_selected は、イベントが起きた点のリストを渡します。点ごとに x、y、curveNumber(何番目の trace か)、pointNumber(何番目の点か)などの値が入っています。

Click a bar
import plotly.graph_objects as go

plotly_click_fig = go.Figure(go.Bar(x=["Mon", "Tue", "Wed", "Thu", "Fri"], y=[12, 19, 7, 15, 22]))
plotly_click_fig.update_layout(height=280)


class PlotlyClickState(rx.State):
    picked: str = "Click a bar"

    @rx.event
    def pick(self, points: list[dict]):
        if points:
            point = points[0]
            self.picked = f"{point['x']}: {point['y']}"


rx.vstack(
    rx.plotly(data=plotly_click_fig, on_click=PlotlyClickState.pick, width="100%"),
    rx.badge(PlotlyClickState.picked, size="2"),
    width="100%",
)

装飾とレイアウト

見た目は図を作るときに update_layout() で決めます。タイトルの位置(title_x)、図・外側の背景色、フォントなどすべてのレイアウト属性は Plotly Layout のドキュメントにあります。

rx.plotly の幅・高さは固定値で指定するより、外側のコンテナのサイズに従わせるのがおすすめです。そうすれば画面サイズに合わせて伸び縮みします。

import plotly.graph_objects as go

plotly_styled_fig = go.Figure(go.Scatter(
    x=[1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992, 1997, 2002, 2007],
    y=[68.75, 69.96, 71.3, 72.13, 72.88, 74.21, 75.76, 76.86, 77.95, 78.61, 79.77, 80.65],
    mode="lines",
    name="Canada",
))
plotly_styled_fig.update_layout(
    title="Life expectancy in Canada",
    title_x=0.5,
    plot_bgcolor="#c3d7f7",
    paper_bgcolor="rgba(128, 128, 128, 0.1)",
    showlegend=True,
    title_font_family="Open Sans",
    title_font_size=25,
)


rx.plotly(data=plotly_styled_fig, width="100%")

Reflex 0.10 には、必要な trace だけを収めた軽量版もあります。rx.plotly.basic、rx.plotly.cartesian、rx.plotly.finance、rx.plotly.geo、rx.plotly.gl2d、rx.plotly.gl3d、rx.plotly.mapbox、rx.plotly.strict は rx.plotly と同じプロパティを受け取りながら、ブラウザがダウンロードする量を減らします(公式ドキュメントにはまだ載っていません)。

注文書を仕上げる

State には選んだ製品名だけを置き、計算値が月別の棒と累積の線を一緒に描きます。累積の線は右の軸(yaxis2)にし、hovermode="x unified" で1か月の値を1つのボックスにまとめます。

import plotly.graph_objects as go

plotly_months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
plotly_sales = {
    "Chairs": [32, 41, 38, 52, 61, 58, 70, 66, 59, 73, 88, 95],
    "Tables": [12, 15, 21, 19, 24, 30, 28, 33, 35, 31, 40, 46],
    "Lamps": [55, 50, 47, 44, 49, 53, 60, 58, 62, 67, 80, 102],
}


class PlotlyOrderState(rx.State):
    product: str = "Chairs"

    @rx.event
    def set_product(self, value: str):
        self.product = value

    @rx.var
    def figure(self) -> go.Figure:
        monthly = plotly_sales[self.product]
        running = [sum(monthly[: i + 1]) for i in range(len(monthly))]
        fig = go.Figure([
            go.Bar(x=plotly_months, y=monthly, name="Monthly"),
            go.Scatter(x=plotly_months, y=running, name="Running total", yaxis="y2", mode="lines+markers"),
        ])
        fig.update_layout(
            title=f"{self.product} sales",
            hovermode="x unified",
            yaxis2={"overlaying": "y", "side": "right"},
            legend={"orientation": "h", "y": -0.2},
            height=360,
        )
        return fig


rx.vstack(
    rx.select(["Chairs", "Tables", "Lamps"], value=PlotlyOrderState.product, on_change=PlotlyOrderState.set_product),
    rx.plotly(data=PlotlyOrderState.figure, width="100%"),
    width="100%",
)

工房ノート

  • fig.show() の代わりに rx.plotly(data=fig)。go で作った図も px で作った図も同じ。

  • layout=dict でレイアウトを上書きし、locale で数値の形式とツールバーの言語を変える。

  • State には単純な値を置き、@rx.var の計算値が go.Figure を返せばチャートがついて変わる。

  • on_click・on_hover・on_selected は点のリスト(x、y、curveNumber、pointNumber …)を渡す。

  • 地図は外部の地図データを取得する。テーマはライト・ダークモードに合わせて自動で切り替わる。

← 前へ

チャートの部品 · Brush

次へ →

ほかのチャートライブラリ · Pyplot

新しい授業・講座のお知らせを受け取る

この講座に授業が追加されたり、続きの講座が公開されたりしたらメールでお知らせします。

収集項目:メールアドレス・目的:この講座の新しい授業・公開のお知らせ・保有期間:解除のご依頼まで。他の目的には使わず、第三者にも提供しません。お知らせメールに返信いただければすぐに削除します。

質問と回答

この回について気になることを書き込んでください。すべての言語のページの質問がここに集まります。

リンクや書式なしで、そのままの文字で表示されます。

R

ReflexKR

触って学ぶPythonとReflex。すべての例はReflex 0.10.0で実際に動かして確認しています。

ReflexKRはバナー広告なし・無料で運営しています。役に立ったら、コーヒー一杯で応援してください。 ☕ コーヒーで応援する

アフィリエイトと支援について
한국어English日本語简体中文EspañolDeutsch

© 2026 ReflexKR · Since 2026 · CC BY-NC 4.0

Built with Reflex