You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

在Flask应用中使用ChartJS生成散点图遇阻求助

在Flask中用ChartJS生成散点图的正确姿势

嘿,我懂你现在的困境——你之前写的模板语法没抓住ChartJS散点图的数据格式要点,咱们马上把它搞定!

首先得明确:ChartJS的散点图要求每个数据点是一个包含xy属性的独立对象,而不是把所有x值和y值分别塞进两个数组里。你的尝试刚好搞反了这个格式,所以才运行不起来。

下面是完整的解决方案,分两步走:

1. Flask后端准备数据

你可以选择在后端直接把身高和体重配对好,再传给模板,这样前端循环更简单:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def show_scatter_plot():
    # 你的原始数据
    height = [168, 170, 180, 190, 200]
    weight = [70, 80, 90, 100, 70]
    # 把两个列表配对成(x,y)元组的列表
    scatter_points = list(zip(height, weight))
    return render_template('scatter.html', points=scatter_points)

2. 前端模板正确渲染ChartJS代码

在你的HTML模板(比如scatter.html)里,用Jinja2循环生成符合要求的散点图数据结构:

<!DOCTYPE html>
<html>
<head>
    <title>身高体重散点图</title>
    <!-- 引入ChartJS -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <!-- 用于绘制图表的画布 -->
    <canvas id="heightWeightChart" width="600" height="400"></canvas>

    <script>
        const ctx = document.getElementById('heightWeightChart').getContext('2d');
        const scatterChart = new Chart(ctx, {
            type: 'scatter',
            data: {
                datasets: [{
                    label: '身高 vs 体重',
                    // 核心:循环后端传来的配对数据,生成{x,y}对象
                    data: [
                        {% for h, w in points %}
                            { x: {{ h }}, y: {{ w }} }{% if not loop.last %},{% endif %}
                        {% endfor %}
                    ],
                    // 自定义点的样式
                    backgroundColor: 'rgba(54, 162, 235, 0.7)',
                    pointRadius: 8,
                    pointHoverRadius: 10
                }]
            },
            options: {
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: '身高 (cm)'
                        }
                    },
                    y: {
                        title: {
                            display: true,
                            text: '体重 (kg)'
                        }
                    }
                }
            }
        });
    </script>
</body>
</html>

如果你不想在后端配对数据

也可以直接把heightweight两个列表传给模板,然后通过索引循环配对:

data: [
    {% for idx in range(height|length) %}
        { x: {{ height[idx] }}, y: {{ weight[idx] }} }{% if not loop.last %},{% endif %}
    {% endfor %}
]

关键注意点

  • 一定要保证每个数据点是{x: 数值, y: 数值}的格式,这是ChartJS散点图的硬性要求
  • loop.last判断避免最后一个点后面多出来的逗号,否则会导致JS语法错误
  • 别忘了引入ChartJS的CDN链接,否则图表根本加载不出来

内容的提问来源于stack exchange,提问作者James Wonder

火山引擎 最新活动