コンポーネント工房: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_pyplot.pyplot公式ドキュメント
工房の注文書
研究室で使っていた matplotlib の図のコードをそのまま Web 画面に載せ、製品を選ぶと図が切り替わるようにしてください。
pyplot は、Matplotlib の図を Reflex の画面に表示するコンポーネントです。別パッケージの reflex-pyplot に入っています。matplotlib.pyplot で作った Figure を渡すとブラウザに描画してくれるので、Flask のルートや画像の base64 変換といった作業は要りません。
このページの例はコードだけを示します。このサイトには matplotlib と reflex-pyplot がインストールされていないためです。下のコードを自分のアプリで実行するには、まず2つのパッケージ(例によっては numpy も)をインストールする必要があります。
matplotlib.pyplot は、Matplotlib を MATLAB のように使えるようにする関数群です。plt.plot、plt.scatter、plt.bar などの呼び出しが、線、棒、文字、凡例を1つずつ図に加えていきます。スクリプトでは最後に plt.show() でウィンドウを開きますが、Reflex アプリでは Figure を pyplot コンポーネントに渡し、State が変わると描き直されます。
すでに Jupyter ノートブック、研究用スクリプト、データパイプラインに matplotlib のコードがあるなら、別のチャートライブラリに移さずそのまま Web アプリで使えます。
棒・折れ線・円のような一般的な業務用チャートには Reflex に組み込まれた Recharts のチャート(rx.recharts)が、拡大・回転のできるインタラクティブな図や 3D の図には rx.plotly が向いています。
reflex-pyplot をインストールするなら matplotlib も必要です。下の例のいくつかは numpy も使います。
pip install reflex-pyplot
# in a project that uses uv
uv add reflex-pyplotfrom reflex_pyplot import pyplot でインポートし、図(Figure)を最初の子として渡します。画面には画像として描画されるので、alt(代替テキスト)、loading、decoding などの画像属性と width、height も一緒に指定します。
import matplotlib.pyplot as plt
import numpy as np
import reflex as rx
from reflex_pyplot import pyplot
def create_contour_plot():
X, Y = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256))
Z = (1 - X / 2 + X**5 + Y**3) * np.exp(-(X**2) - Y**2)
levels = np.linspace(Z.min(), Z.max(), 7)
fig, ax = plt.subplots()
ax.contourf(X, Y, Z, levels=levels)
plt.close(fig)
return fig
def pyplot_simple_example():
return rx.card(
pyplot(
create_contour_plot(),
alt="Filled contour plot of a two-dimensional function",
loading="lazy",
decoding="async",
width="100%",
height="400px",
),
bg_color="#ffffff",
width="100%",
)図を作ったあとは必ず plt.close(fig) で閉じます。閉じないとサーバーが図を保持し続け、メモリが増えていきます。図の色は Matplotlib が決めるので、ダークテーマでも白い背景が見えるよう rx.card(bg_color="#ffffff") で包みました。
いちばんよくある図です。スクリプトと同じように plt.subplots() と ax.plot() で作り、図を pyplot に渡します。
import matplotlib.pyplot as plt
import numpy as np
import reflex as rx
from reflex_pyplot import pyplot
def create_line_plot():
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), label="sin(x)")
ax.plot(x, np.cos(x), label="cos(x)")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.close(fig)
return fig
def pyplot_line_example():
return rx.card(
pyplot(
create_line_plot(),
alt="Sine and cosine curves from zero to ten",
loading="lazy",
decoding="async",
width="100%",
height="400px",
),
bg_color="#ffffff",
width="100%",
)ax.bar() にカテゴリと値を渡すこと以外は同じやり方です。
import matplotlib.pyplot as plt
import reflex as rx
from reflex_pyplot import pyplot
def create_bar_chart():
fruits = ["apples", "oranges", "bananas", "pears"]
counts = [23, 17, 35, 29]
fig, ax = plt.subplots()
ax.bar(fruits, counts, color="#4e79a7")
ax.set_ylabel("count")
ax.set_title("Fruit inventory")
plt.close(fig)
return fig
def pyplot_bar_example():
return rx.card(
pyplot(
create_bar_chart(),
alt="Fruit inventory: apples 23, oranges 17, bananas 35, pears 29",
loading="lazy",
decoding="async",
width="100%",
height="400px",
),
bg_color="#ffffff",
width="100%",
)ランダムな点を打つ散布図に、シャッフルボタンと点の数のスライダーを付けます。図は @rx.var の計算値が作るので、State の値が変わると描き直されます。イベントに throttle=500 を指定して、0.5秒に1回だけ描き直すようにしました。
Matplotlib の図の色はアプリのテーマに従いません。そこで明るい図と暗い図の両方を作り、rx.color_mode_cond で現在のモードに合うほうを表示します。
import random
import matplotlib.pyplot as plt
import numpy as np
import reflex as rx
from matplotlib.figure import Figure
from reflex_pyplot import pyplot
def create_plot(theme: str, plot_data: tuple, scale: list):
bg_color, text_color = ("#1e1e1e", "white") if theme == "dark" else ("white", "black")
grid_color = "#555555" if theme == "dark" else "#cccccc"
fig, ax = plt.subplots(facecolor=bg_color)
ax.set_facecolor(bg_color)
for (x, y), color in zip(plot_data, ["#4e79a7", "#f28e2b"]):
ax.scatter(x, y, c=color, s=scale, label=color, alpha=0.6, edgecolors="none")
ax.legend(loc="upper right", facecolor=bg_color, edgecolor="none", labelcolor=text_color)
ax.grid(True, color=grid_color)
ax.tick_params(colors=text_color)
for spine in ax.spines.values():
spine.set_edgecolor(text_color)
for item in [ax.xaxis.label, ax.yaxis.label, ax.title]:
item.set_color(text_color)
plt.close(fig)
return fig
class PyplotState(rx.State):
num_points: int = 25
plot_data: tuple = tuple(np.random.rand(2, 25) for _ in range(2))
scale: list = [random.uniform(0, 100) for _ in range(25)]
@rx.event(temporal=True, throttle=500)
def randomize(self):
self.plot_data = tuple(np.random.rand(2, self.num_points) for _ in range(2))
self.scale = [random.uniform(0, 100) for _ in range(self.num_points)]
@rx.event(temporal=True, throttle=500)
def set_num_points(self, num_points: list[int | float]):
self.num_points = int(num_points[0])
yield PyplotState.randomize()
@rx.var
def fig_light(self) -> Figure:
return create_plot("light", self.plot_data, self.scale)
@rx.var
def fig_dark(self) -> Figure:
return create_plot("dark", self.plot_data, self.scale)
def pyplot_example():
return rx.vstack(
rx.card(
rx.color_mode_cond(
pyplot(PyplotState.fig_light, alt="Scatter plot of the current randomized points", width="100%", height="100%"),
pyplot(PyplotState.fig_dark, alt="Scatter plot of the current randomized points", width="100%", height="100%"),
),
rx.hstack(
rx.button("Randomize", on_click=PyplotState.randomize),
rx.text("Number of Points:"),
rx.slider(default_value=25, min=10, max=100, on_value_commit=PyplotState.set_num_points),
width="100%",
),
width="100%",
),
justify_content="center",
align_items="center",
width="100%",
)公式ドキュメントの例のスライダーには min_=10 と書かれていますが、Reflex 0.10 の rx.slider ではその名前は最小値ではなく CSS スタイルとして扱われます。上のコードは min=10 に直しました。また、この例は numpy 配列を State に入れていますが、実際のアプリでは State にリストのような単純な値を置き、図を作るときに配列に変換するほうが安全です。
Web ページに Matplotlib の図をどう表示しますか?いつもどおり図を作り、その Figure を pyplot コンポーネントに渡します。Flask、REST のルート、base64 変換は要りません。
Matplotlib の図をインタラクティブにできますか?はい。State に依存する rx.var の中で図を作り、ボタン・スライダーなどのイベントで State を変えると、図が自動で描き直されます(上の State の例)。
plt.show() を呼ぶ必要はありますか?いいえ。plt.show() はデスクトップのウィンドウを開く関数なので、Web アプリでは使いません。図を返して plt.close(fig) で閉じます。
pyplot は Matplotlib の図を1つ表示します。独自に定義されたプロパティやイベントはなく、すべてのコンポーネントにある基本イベント(on_click、on_mount など)を受け取ります。
| 引数 | 値 | 用途 |
|---|---|---|
| 最初の子 | matplotlib.figure.Figure またはそれを返す State の値 | 表示する図 |
alt · loading · decoding | 文字列 | 画像の代替テキスト、遅延読み込み、非同期デコード |
width · height | CSS のサイズ | 図が占めるサイズ |
State には選んだ製品名だけを置き、計算値がその製品の棒グラフを作ります。このコードも、reflex-pyplot と matplotlib をインストールしたアプリで実行します。
import matplotlib.pyplot as plt
import reflex as rx
from matplotlib.figure import Figure
from reflex_pyplot import pyplot
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
SALES = {"Chairs": [32, 41, 38, 52, 61, 58], "Tables": [12, 15, 21, 19, 24, 30]}
class PyplotReportState(rx.State):
product: str = "Chairs"
@rx.event
def set_product(self, value: str):
self.product = value
@rx.var
def figure(self) -> Figure:
fig, ax = plt.subplots(figsize=(6, 3))
ax.bar(MONTHS, SALES[self.product], color="#4e79a7")
ax.set_title(f"{self.product} sales")
ax.set_ylabel("units")
fig.tight_layout()
plt.close(fig)
return fig
def pyplot_report():
return rx.vstack(
rx.select(["Chairs", "Tables"], value=PyplotReportState.product, on_change=PyplotReportState.set_product),
rx.card(
pyplot(PyplotReportState.figure, alt="Monthly sales of the selected product", width="100%"),
bg_color="#ffffff",
width="100%",
),
width="100%",
)工房ノート
pip install reflex-pyplot(matplotlib が必要)。from reflex_pyplot import pyplot。
pyplot(fig, alt=…, width=…) のように Figure を最初の子として渡す。plt.show() は使わない。
図を作ったら plt.close(fig) で必ず閉じる。
@rx.var の計算値が Figure を返せば、State が変わったときに描き直される。
色はテーマに従わないので、color_mode_cond で明るい図と暗い図を分ける。
新しい授業・講座のお知らせを受け取る
この講座に授業が追加されたり、続きの講座が公開されたりしたらメールでお知らせします。
R
ReflexKR
触って学ぶPythonとReflex。すべての例はReflex 0.10.0で実際に動かして確認しています。
ReflexKRはバナー広告なし・無料で運営しています。役に立ったら、コーヒー一杯で応援してください。 ☕ コーヒーで応援する
アフィリエイトと支援について© 2026 ReflexKR · Since 2026 · CC BY-NC 4.0
質問と回答
この回について気になることを書き込んでください。すべての言語のページの質問がここに集まります。