Reflex + Plotly 完整实战指南:用纯 Python 在 Web 应用中渲染交互式图表
2026/9/12 6:48:57 网站建设 项目流程

Reflex + Plotly 完整实战指南:用纯 Python 在 Web 应用中渲染交互式图表

【免费下载链接】reflex🕸️ Web apps in pure Python 🐍项目地址: https://gitcode.com/GitHub_Trending/re/reflex

导读

Plotly 是 Python 生态中最流行的交互式图表库之一,而 Reflex 通过rx.plotly组件将其无缝封装进全栈 Web 应用。本文基于 Reflex 官方文档 docs/library/graphing/other-charts/plotly.md 展开,结合仓库中rx.plotly的组件源码与测试用例,系统讲解如何用纯 Python 在 Reflex 中嵌入折线图、散点图、热力图、3D 曲面图、K 线图、地图、桑基图等各类 Plotly 图表。读完本文,你将掌握rx.plotly的核心用法、图表状态的动态更新、locale本地化配置、图表样式定制等实战能力。

安装与前置条件

在 Reflex 中使用 Plotly,需要安装 Python 的 plotly 库:

pip install plotly

仓库中的 plotly 组件包reflex-components-plotly在 packages/reflex-components-plotly/pyproject.toml 中声明了依赖reflex-base >= 0.9.0reflex-components-core >= 0.9.0。Plotly 是可选依赖,未安装时组件源码会在 packages/reflex-components-plotly/src/reflex_components_plotly/plotly.py 中输出警告Plotly is not installed. Please run pip install plotly.

从源码结构看,rx.plotly组件底层依赖 react-plotly.js@4.1.0 和plotly.js@3.7.0,这些前端依赖会在 Reflex 编译时自动加载,无需手动安装。

基础用法:rx.plotly 组件

核心概念:为什么不用 fig.show()

在 Plotly 的普通 Python 脚本中,通常用fig.show()来展示图表。但在 Reflex 的 UI 代码中,必须改用rx.plotly(data=fig)来渲染图表,这是 Reflex 与普通 Python 脚本在使用上的关键区别。

import reflex as rx import plotly.express as px df = px.data.gapminder().query("country=='Canada'") fig = px.line(df, x="year", y="lifeExp", title="Life expectancy in Canada") def line_chart(): return rx.center( rx.plotly(data=fig), )

rx.plotly 组件源码解析

rx.plotly的核心实现位于 packages/reflex-components-plotly/src/reflex_components_plotly/plotly.py,其关键属性包括:

属性类型说明
dataVar[Figure]要显示的 Plotly figure 或 plotly 数据 JSON
layoutVar[dict]图表的布局配置
templateVar[Template]图表的视觉模板(默认自动适配深浅色模式)
configVar[dict]Plotly 图表的配置项
localeVar[str]本地化代码,用于数字/日期格式和模式栏标签
use_resize_handlerVar[bool]是否在窗口尺寸变化时自动调整图表大小(默认True

Plotly类继承自NoSSRComponent,这意味着图表只在客户端渲染(避免服务端渲染时无法访问浏览器 API)。

从源码中的create类方法(plotly.py)可以看到,rx.plotly默认会使用color_mode_cond根据 Reflex 应用的明暗模式自动选择plotlyplotly_dark模板,实现图表与主题的自动适配:

responsive_template = color_mode_cond( light=LiteralVar.create(templates["plotly"]), dark=LiteralVar.create(templates["plotly_dark"]), )

Figure 的序列化机制

在 Reflex 中,Plotly figure 会被自动序列化为 JSON 传给前端。这个序列化器定义在 packages/reflex-base/src/reflex_base/utils/serializers.py:

@serializer def serialize_figure(figure: Figure) -> dict: """Serialize a plotly figure.""" return json.loads(str(to_json(figure)))

也就是说,data属性既可以传 Plotly 的go.Figure对象,也可以传符合 Plotly 规范的 JSON 字典。测试用例 tests/units/components/graphing/test_plotly.py 中验证了这一行为:

def test_serialize_plotly(plotly_fig: go.Figure): value = serialize(plotly_fig) assert isinstance(value, dict) assert value == serialize_figure(plotly_fig)

Plotly Express 图表类型速览

Plotly Express(plotly.express,通常导入为px)可以用一行 Python 代码创建常见图表类型,所有类型的 figure 都可以直接通过rx.plotly渲染。以下是各类图表的完整示例。

柱状图 Bar Chart

import plotly.express as px oceania = px.data.gapminder().query("continent == 'Oceania'") bar_fig = px.bar( oceania, x="year", y="pop", color="country", title="Population of Oceania" ) def plotly_bar_chart(): return rx.center(rx.plotly(data=bar_fig))

散点图 Scatter Plot

iris = px.data.iris() scatter_fig = px.scatter( iris, x="sepal_width", y="sepal_length", color="species", title="Iris sepal dimensions", ) def plotly_scatter_plot(): return rx.center(rx.plotly(data=scatter_fig))

饼图 Pie Chart

tips = px.data.tips() pie_fig = px.pie(tips, values="tip", names="day", title="Tips by day") def plotly_pie_chart(): return rx.center(rx.plotly(data=pie_fig))

热力图 Heatmap

tips_data = px.data.tips() heatmap_fig = px.density_heatmap( tips_data, x="total_bill", y="tip", title="Bill vs tip density heatmap" ) def plotly_heatmap(): return rx.center(rx.plotly(data=heatmap_fig))

直方图 Histogram

hist_data = px.data.tips() histogram_fig = px.histogram( hist_data, x="total_bill", nbins=20, title="Distribution of total bills" ) def plotly_histogram(): return rx.center(rx.plotly(data=histogram_fig))

箱线图 Box Plot

box_data = px.data.tips() box_fig = px.box(box_data, x="day", y="total_bill", title="Total bill by day") def plotly_box_plot(): return rx.center(rx.plotly(data=box_fig))

气泡图 Bubble Chart

气泡图是一种散点图,用标记(marker)的大小展示第三个数据维度。用px.scatter并传入size参数即可创建:

gapminder = px.data.gapminder() bubble_fig = px.scatter( gapminder.query("year==2007"), x="gdpPercap", y="lifeExp", size="pop", color="continent", hover_name="country", log_x=True, size_max=60, title="GDP per capita vs life expectancy (2007)", ) def plotly_bubble_chart(): return rx.center(rx.plotly(data=bubble_fig))

甘特图 Gantt Chart

甘特图是一种项目进度表:任务列在纵轴,时间区间在横轴,每个条形宽度表示活动持续时间。用px.timeline创建:

import pandas as pd tasks = pd.DataFrame([ dict(Task="Job A", Start="2009-01-01", Finish="2009-02-28"), dict(Task="Job B", Start="2009-03-05", Finish="2009-04-15"), dict(Task="Job C", Start="2009-02-20", Finish="2009-05-30"), ]) gantt_fig = px.timeline(tasks, x_start="Start", x_end="Finish", y="Task") # 反转 y 轴,使任务从上到下排列 gantt_fig.update_yaxes(autorange="reversed") def plotly_gantt_chart(): return rx.center(rx.plotly(data=gantt_fig))

旭日图 Sunburst Chart

旭日图从根到叶以径向方式展示层次数据:根节点在圆心,子节点分布在同心圆环上。用px.sunburst并通过namesparents定义层级:

family = dict( character=["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"], parent=["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve"], value=[10, 14, 12, 10, 2, 6, 6, 4, 4], ) sunburst_fig = px.sunburst(family, names="character", parents="parent", values="value") def plotly_sunburst_chart(): return rx.center(rx.plotly(data=sunburst_fig))

漏斗图 Funnel Chart

漏斗图展示数据经过业务流程各阶段时的变化,常用于商业智能分析中定位流程损耗点。用px.funnel创建:

funnel_data = dict( number=[39, 27.4, 20.6, 11, 2], stage=[ "Website visit", "Downloads", "Potential customers", "Requested price", "Invoice sent", ], ) funnel_fig = px.funnel(funnel_data, x="number", y="stage") def plotly_funnel_chart(): return rx.center(rx.plotly(data=funnel_fig))

3D 图表

3D 曲面图

下面以 Mount Bruno 的 3D 曲面图为例,说明如何用go.Figure+go.Surface在 Reflex 中渲染 3D 图表。任何 Plotly figure 都可以用同样的方式封装。

import plotly.graph_objects as go import pandas as pd # 从 CSV 读取数据(文件位于 docs/app/data/mt_bruno_elevation.csv) z_data = pd.read_csv("data/mt_bruno_elevation.csv") fig = go.Figure(data=[go.Surface(z=z_data.values)]) fig.update_traces( contours_z=dict( show=True, usecolormap=True, highlightcolor="limegreen", project_z=True ) ) 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) ) def mountain_surface(): return rx.center( rx.plotly(data=fig), )

📊 数据集来源:mt_bruno_elevation.csv(仓库中已包含此示例数据文件)

3D 散点图

px.scatter_3d一次性展示三个变量之间的关系,并可用第四个变量映射为颜色:

iris_3d = px.data.iris() scatter_3d_fig = px.scatter_3d( iris_3d, x="sepal_length", y="sepal_width", z="petal_width", color="species", ) def scatter_3d_chart(): return rx.center(rx.plotly(data=scatter_3d_fig))

3D 坐标轴配置

3D 图表的 trace 放置在 scene 中,每个 scene 轴通过 figure 的scenelayout 配置——可以逐轴设置nticksrange或轴标题。下面是一个go.Mesh3d点云示例,三个轴都设置了自定义刻度数和范围:

import numpy as np import plotly.graph_objects as go np.random.seed(1) N = 70 mesh_fig = go.Figure( data=[ go.Mesh3d( x=(70 * np.random.randn(N)), y=(55 * np.random.randn(N)), z=(40 * np.random.randn(N)), opacity=0.5, color="rgba(244,22,100,0.6)", ) ] ) 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), ) def axis_3d_chart(): return rx.center(rx.plotly(data=mesh_fig))

金融图表

K 线图 Candlestick Chart

K 线图描述给定 x 坐标(通常是时间)上的开盘、最高、最低、收盘价:箱体展示开盘价与收盘价之间的范围,线条展示最低价与最高价之间的范围。用go.Candlestick创建:

import plotly.graph_objects as go import pandas as pd candles = pd.DataFrame({ "Date": [ "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], }) candlestick_fig = go.Figure( data=[ go.Candlestick( x=candles["Date"], open=candles["Open"], high=candles["High"], low=candles["Low"], close=candles["Close"], ) ] ) candlestick_fig.update_layout( title=dict(text="AAPL Stock Price"), yaxis=dict(title=dict(text="AAPL Stock")), ) def candlestick_chart(): return rx.center(rx.plotly(data=candlestick_fig))

瀑布图 Waterfall Chart

瀑布图展示初始值如何被一系列正向和负向变化影响——例如利润表。用go.Waterfall创建,并通过measure参数把每个值标记为"relative"(相对变化)或"total"(累计值):

waterfall_fig = go.Figure( go.Waterfall( name="20", 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)"}}, ) ) waterfall_fig.update_layout(title="Profit and loss statement 2018", showlegend=True) def waterfall_chart(): return rx.center(rx.plotly(data=waterfall_fig))

子弹图 Bullet Chart

子弹图由 Stephen Few 设计,作为仪表盘仪表/刻度的紧凑替代品,将定量条形、定性范围(steps)和性能阈值线组合在一个简洁布局中。用go.Indicator搭配"bullet"仪表形状构建:

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"}, }, ) ).update_layout(height=250) def bullet_chart(): return rx.center(rx.plotly(data=bullet_fig))

统计图表

连续误差带 Continuous Error Bands

连续误差带用主 trace 周围的阴影区域表示误差或不确定性,而不是离散的须状误差棒。用go.Scatter先绘制主线条,再绘制第二条 trace:正向遍历上界、反向遍历下界,并用fill="toself"填充:

band_x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] band_y = [1, 2, 7, 4, 5, 6, 7, 8, 9, 10] band_y_upper = [2, 3, 8, 5, 6, 7, 8, 9, 10, 11] band_y_lower = [0, 1, 5, 3, 4, 5, 6, 7, 8, 9] error_band_fig = go.Figure([ go.Scatter( x=band_x, y=band_y, line=dict(color="rgb(0,100,80)"), mode="lines", ), go.Scatter( x=band_x + band_x[::-1], # x,然后是反向的 x y=band_y_upper + band_y_lower[::-1], # 上界,然后是反向的下界 fill="toself", fillcolor="rgba(0,100,80,0.2)", line=dict(color="rgba(255,255,255,0)"), hoverinfo="skip", showlegend=False, ), ]) def continuous_error_bands_chart(): return rx.center(rx.plotly(data=error_band_fig))

地图

地理地图 Geo Map

Geo 地图是基于地理要素的轮廓地图,而非地图瓦片。用px.scatter_geopx.line_geopx.choropleth创建的 figure——或者包含go.Scattergeogo.Choroplethtrace 的 figure——将地图配置存储在 figure 的layout.geo对象中,可用update_geos调整:

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.center(rx.plotly(data=geo_fig))

散点地图 Scatter Map

散点地图在基于瓦片的地图上按数据绘制标记,用大小和颜色编码数据——适合可视化车辆位置、门店分布等地理点数据。用px.scatter_map创建(或使用go.Scattermaptrace 进行更底层的控制):

carshare = px.data.carshare() map_fig = px.scatter_map( carshare, lat="centroid_lat", lon="centroid_lon", color="peak_hour", size="car_hours", color_continuous_scale=px.colors.cyclical.IceFire, size_max=15, zoom=10, ) def scatter_map_chart(): return rx.center(rx.plotly(data=map_fig))

表格与图表

表格 Table

Plotly 也能将数据渲染成交互式表格。用go.Table创建,列标题传给header,列数据传给cells

table_fig = go.Figure( data=[ go.Table( header=dict(values=["A Scores", "B Scores"]), cells=dict(values=[[100, 90, 80, 90], [95, 85, 75, 95]]), ) ] ) def plotly_table(): return rx.center(rx.plotly(data=table_fig))

桑基图 Sankey Diagram

桑基图是流程图,箭头宽度与流量成正比。用go.Sankey创建,通过索引定义节点以及节点间的链接:

sankey_fig = go.Figure( data=[ 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( # 索引对应节点标签,例如 A1, A2, B1, ... source=[0, 1, 0, 2, 3, 3], target=[2, 3, 3, 4, 4, 5], value=[8, 4, 2, 8, 4, 2], ), ) ] ) sankey_fig.update_layout(title_text="Basic Sankey Diagram", font_size=10) def plotly_sankey_diagram(): return rx.center(rx.plotly(data=sankey_fig))

Locale 本地化配置

locale参数可以本地化 Plotly 的数字/日期格式以及模式栏(modebar)标签:

df = px.data.gapminder().query("country=='Canada'") fig = px.line(df, x="year", y="lifeExp", title="Life expectancy in Canada") def localized_line_chart(): return rx.center( rx.plotly( data=fig, locale="de", ), )

同时仍可以传config;当两者都提供时,locale=会作为最终的 locale 值叠加到 config 之上。

locale 的底层实现

从源码看,当设置locale时,组件会动态引入 plotly.js-locales@3.7.0 的 locale 字典,并注入到 plot 的config.locales中,再通过_rxGetPlotlyLocaleConfig这个自定义 JS 函数将 locale 与用户提供的config合并(plotly.py):

const _rxGetPlotlyLocaleConfig = (config, locale, plotlyLocales) => { const localeData = _rxResolvePlotlyLocaleData(plotlyLocales, locale); if (!localeData) { return { ...config, locale: String(locale) }; } const localeName = localeData?.name ?? String(locale); return { ...config, locale: localeName, locales: { ...(config?.locales ?? {}), [localeName]: localeData, }, }; };

测试用例 tests/units/components/graphing/test_plotly.py 验证了 locale 会合并进 config 而非覆盖:

def test_plotly_locale_option_merges_into_config(plotly_fig: go.Figure): component = rx.plotly(data=plotly_fig, locale="de") rendered = component._render() config_var = rendered.props.get("config") assert config_var is not None assert "locale" not in rendered.props assert "_rxGetPlotlyLocaleConfig" in str(config_var) assert "de" in str(config_var)

Playwright 集成测试 tests/integration/tests_playwright/test_plotly.py 还验证了不同 locale 下模式栏按钮提示文案的实际渲染效果——例如德语下 "Autoscale" 显示为 "Automatische Skalierung"、法语下显示为 "Échelle automatique",并且确认 locale 与 state 驱动的config(如移除 lasso 按钮)可以正确合并共存。

图表作为 State 变量:运行时动态更新

如果把 figure 设置为 state 变量,就可以在运行时动态更新图表。下面的示例中,用户通过下拉框切换国家,图表实时重绘:

import plotly.express as px import plotly.graph_objects as go import pandas as pd class PlotlyState(rx.State): df: pd.DataFrame figure: go.Figure = px.line() @rx.event def create_figure(self): self.df = px.data.gapminder().query("country=='Canada'") self.figure = px.line( self.df, x="year", y="lifeExp", title="Life expectancy in Canada", ) @rx.event def set_selected_country(self, country): self.df = px.data.gapminder().query(f"country=='{country}'") self.figure = px.line( self.df, x="year", y="lifeExp", title=f"Life expectancy in {country}", ) def line_chart_with_state(): return rx.vstack( rx.select( ["China", "France", "United Kingdom", "United States", "Canada"], default_value="Canada", on_change=PlotlyState.set_selected_country, ), rx.plotly( data=PlotlyState.figure, on_mount=PlotlyState.create_figure, ), )

关键点:

  • figure字段的初始值px.line()保证 state 初始化时就有合法的 Plotly figure;
  • 通过on_mount=PlotlyState.create_figure在页面加载时触发图表创建;
  • 用户切换下拉框时,set_selected_country事件重新查询数据并重建 figure,rx.plotly会自动重绘。

事件处理器:让图表与用户交互

rx.plotly组件支持丰富的 Plotly 事件处理器(定义在 plotly.py):

事件触发时机
on_click点击图表时(携带点数据)
on_hover/on_unhover鼠标悬停/移出图表元素时(携带点数据)
on_selected/on_selecting选中/正在拖拽选择图表元素时
on_deselect清除选择时(双击)
on_double_click双击图表时
on_relayout/on_relayouting图表布局变化后/过程中(缩放、平移等)
on_restyle图表样式变化后
on_redraw/on_after_plot图表重绘后
on_animated/on_transitioning动画完成后/进行中
on_button_clicked点击 Plotly UI 按钮时
on_autosize图表响应式调整大小时

携带点数据的事件(如on_clickon_hover)会通过extractPointsJS 函数提取事件数据中的点信息(坐标x/y/z、经纬度lat/loncurveNumberpointIndexbbox等),这些字段在 plotly.py 的PointTypedDict 中定义。

样式与布局定制

update_layout()方法定制图表布局。所有布局属性可参考 Plotly Layouts。

⚠️注意:官方不推荐在 figure 中显式设置 width 和 height 属性,建议保持图表对外层容器响应式,尺寸由外层容器决定。

df = px.data.gapminder().query("country=='Canada'") fig_1 = px.line( df, x="year", y="lifeExp", title="Life expectancy in Canada", ) fig_1.update_layout( 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, ) def add_styles(): return rx.center( rx.plotly(data=fig_1), width="100%", height="100%", )

使用 use_resize_handler 保持响应式

rx.plotly默认启用use_resize_handler=True,当窗口尺寸变化时图表会自动调整大小(源码中 plotly.py 的默认值为True)。如果希望在容器尺寸变化时也能自动适配,可结合 Reflex 的响应式布局组件使用。

按需加载的 Plotly 变体

rx.plotly默认引入完整的plotly.js构建。如果希望减小前端打包体积,可以使用 PlotlyNamespace 提供的按需加载变体:

变体说明
rx.plotly.basic基础 2D 图表(plotly.js-basic-dist-min)
rx.plotly.cartesian笛卡尔坐标系图表(plotly.js-cartesian-dist-min)
rx.plotly.geo地理图表(plotly.js-geo-dist-min)
rx.plotly.gl3d3D 图表(plotly.js-gl3d-dist-min)
rx.plotly.gl2d2D WebGL 图表(plotly.js-gl2d-dist-min)
rx.plotly.mapboxMapbox 地图(plotly.js-mapbox-dist-min)
rx.plotly.finance金融图表(plotly.js-finance-dist-min)
rx.plotly.strict严格模式图表(plotly.js-strict-dist-min)

这些变体通过动态 import(ClientSide+createPlotlyComponent)按需加载对应的 plotly.js 发行版,例如:

import reflex as rx import plotly.graph_objects as go fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[3, 1, 2])]) def basic_chart(): return rx.center( rx.plotly.basic(data=fig), # 只加载基础的 plotly.js-basic-dist-min )

集成测试 tests/integration/tests_playwright/test_plotly.py 使用rx.plotly.basic(data=figure, locale="fr")验证了动态变体同样支持 locale 合并。

常见问题与最佳实践

图表不显示怎么办?

  1. 确认在 UI 代码中使用了rx.plotly(data=fig)而非fig.show()——fig.show()只在普通 Python 脚本中有效;
  2. 确认安装了 plotlypip install plotly,否则组件会输出警告并可能无法渲染;
  3. 确认 figure 是合法的 Plotly figure 或 JSON 字典——data属性最终会被序列化为 JSON 传给前端。

为什么图表尺寸不受控制?

width/height应在外层 Reflex 容器上设置(如rx.center(..., width="100%", height="100%")),不要在 figure 的update_layout中设置,否则图表无法对外层容器保持响应式。

如何让图表响应式?

默认use_resize_handler=True,窗口 resize 时自动调整。若图表嵌在动态变化的容器中,确保外层容器有明确的尺寸。

图表太大导致前端打包体积大?

根据图表类型选择对应的动态变体(rx.plotly.basicrx.plotly.finance等),只加载所需 plotly.js 子集,可以显著减小打包体积。

总结

本文完整梳理了 Reflex 中rx.plotly组件的使用方式:从基础的折线图、各类 Plotly Express 图表,到 3D 曲面、金融 K 线、瀑布图、子弹图、连续误差带、地理地图、桑基图等高级图表,再到 locale 本地化、State 驱动动态更新、样式定制与按需加载。结合 packages/reflex-components-plotly/src/reflex_components_plotly/plotly.py 的源码与 tests/units/components/graphing/test_plotly.py、tests/integration/tests_playwright/test_plotly.py 的测试验证,rx.plotly的核心价值在于:无需任何 JavaScript,纯 Python 即可构建交互式、可动态更新、支持本地化的数据可视化 Web 应用。你可以将文中的示例直接复制到 Reflex 项目中运行,也可以把任意 Plotly figure 用相同的方式封装进自己的应用。

延伸阅读

  • Plotly Express 图表类型文档
  • 数据可视化组件总览
  • State 变量系统
  • 事件处理器详解
  • 示例数据集

【免费下载链接】reflex🕸️ Web apps in pure Python 🐍项目地址: https://gitcode.com/GitHub_Trending/re/reflex

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询