FastAPI中如何为Plotly图表配置点击事件处理程序?
解决FastAPI中Plotly图表的plotly_click事件绑定问题
针对你遇到的TypeError: graphContainer.on is not a function错误,下面分两种渲染方式给出具体的事件配置方案:
方式一:通过Plotly.react渲染JSON格式图表
FastAPI后端代码
from fastapi import FastAPI, Request from fastapi.templating import Jinja2Templates import plotly.express as px import json import plotly app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get("/graph-json") async def get_graph_json(): df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length") # 将图表转为JSON格式 graph_json = json.dumps(fig.to_dict(), cls=plotly.utils.PlotlyJSONEncoder) return {"graph_json": graph_json} @app.get("/") async def render_graph(request: Request): return templates.TemplateResponse("graph_json.html", {"request": request})
前端模板(graph_json.html)
<!DOCTYPE html> <html> <head> <!-- 引入Plotly.js --> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <div id="graph-container"></div> <script> // 获取原生DOM图表容器 const graphContainer = document.getElementById('graph-container'); // 从后端拉取图表数据并渲染 fetch('/graph-json') .then(response => response.json()) .then(data => { // 渲染图表 Plotly.react(graphContainer, data.graph_json.data, data.graph_json.layout); // 绑定plotly_click事件 graphContainer.on('plotly_click', function(clickData){ const points = clickData.points; if(points.length > 0){ const x = points[0].x; const y = points[0].y; console.log(`点击坐标:x=${x}, y=${y}`); // 可在此添加数据上报等后续逻辑 } }); }); </script> </body> </html>
注意:必须确保graphContainer是原生DOM元素,事件绑定要放在Plotly.react执行完成后,保证图表已初始化。
方式二:通过fig.to_html生成HTML代码渲染
FastAPI后端代码
from fastapi import FastAPI, Request from fastapi.templating import Jinja2Templates import plotly.express as px app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get("/") async def render_graph(request: Request): df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length") # 生成HTML代码,通过CDN引入Plotly.js避免重复加载 graph_html = fig.to_html(include_plotlyjs='cdn', full_html=False) return templates.TemplateResponse("graph_html.html", {"request": request, "graph_html": graph_html})
前端模板(graph_html.html)
<!DOCTYPE html> <html> <body> <!-- 插入生成的图表HTML --> <div id="graph-container">{{ graph_html|safe }}</div> <script> // 等待页面完全加载,确保图表初始化完成 window.addEventListener('load', function(){ // 定位到Plotly自动生成的图表元素 const graphElement = document.querySelector('#graph-container .plotly-graph-div'); if(graphElement){ // 绑定plotly_click事件 graphElement.on('plotly_click', function(clickData){ const points = clickData.points; if(points.length > 0){ const x = points[0].x; const y = points[0].y; console.log(`点击坐标:x=${x}, y=${y}`); } }); } }); </script> </body> </html>
注意:
fig.to_html生成的图表会在容器内创建带.plotly-graph-div类的元素,需通过该类选择器定位实际图表元素。- 事件绑定放在
window.load回调中,避免因图表未渲染完成导致的元素不存在问题。
错误原因总结
出现graphContainer.on is not a function通常是以下情况:
- 获取的元素不是原生DOM元素(比如用jQuery选择器未转换为原生元素)。
- Plotly.js未正确加载,导致DOM元素未挂载Plotly事件方法。
- 事件绑定时机过早,图表尚未完成初始化。
内容的提问来源于stack exchange,提问作者Vaibhav Agrawal
相关产品推荐
相关产品推荐

