带有JS JS Scatter Plot斗争的烧瓶

时间:2018-04-19 18:30:43

标签: python flask chart.js jinja2

我想使用ChartJS在Flask App中生成散点图。我有两个清单:

height=[168,170,180,190,200]
weight=[70,80,90,100,70]

我找不到如何使用Flask中的ChartJS列表的示例。我的解决方案不起作用。我的逻辑是否有某种解决方案:

var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
    datasets: [{
        label: 'Scatter Dataset',
        data: [{
            x: [{% for item in height }]
                        {{item}},
                      {% endfor %}],

            y: [{% for item in weight }]
                        {{item}},
                      {% endfor %}]
        }
    }]
},

options: {
    scales: {
        xAxes: [{
            type: 'linear',
            position: 'bottom'
        }]
    }
}
});

谢谢

更新基于@Joost答案的HTML模板

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chart</title>
</head>
<body>



 <canvas id="myChart1" width="400" height="400"></canvas>
 <script 
 src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"> 
 </script>

    <script>
    var ctx = document.getElementById("myChart1").getContext('2d');
    var myChart = new Chart(ctx, {
    type: 'scatter',
    data: {
       datasets: [{
        label: 'Scatter Dataset',
        data: [{
            x: {{height}},
            y: {{weight}}

        }]
    }]
},
options: {
    scales: {
        xAxes: [{
            type: 'linear',
            position: 'bottom'
         }]
      }
   }
 });
  </script>

  </body>
  </html>

2 个答案:

答案 0 :(得分:0)

您的语法已关闭。您正在打印[] 170,] 170,] 180,]

由于列表在python和js中具有相同的语法,因此您只需将其直接插入到js中即可。

data: [{
        x: {{height}},
        y: {{weight}}
       }

编辑:

最小的工作示例:

from flask import Flask, render_template_string
app = Flask(__name__)

@app.route('/')
def hello_world():
    heights=[168,170,180,190,200]
    weights=[70,80,90,100,70]
    newlist = []
    for h, w in zip(heights, weights):
        newlist.append({'x': h, 'y': w})
    ugly_blob = str(newlist).replace('\'', '')

    return render_template_string(
    '''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chart</title>
</head>
<body>
   <canvas id="myChart1" width="40px" height="40px"></canvas>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
   <script>
   new Chart.Scatter(document.getElementById("myChart1"), {
   type: 'scatter',
   data: {
     datasets: [{
       label: 'Scatter Dataset',
       data: {{ data }},
       showLine: false,
       borderColor: "blue",
       backgroundColor: "blue"
     }]
   }
 });
  </script>
</body>
</html>
''', data=ugly_blob)

app.run()

答案 1 :(得分:0)

Joost帮助很大!

传递字符串是一个问题。例如,如果需要borderColor,则需要将其作为全局元素传递:

    Chart.defaults.global.elements.point.borderColor = 'black';

来自https://www.chartjs.org/docs/latest/configuration/elements.html