具有JSON列表变量的ChartJS散点图不起作用

时间:2019-07-18 06:26:49

标签: javascript flask chart.js

我想从我从Flask传递的JSON变量(列表列表;以Chart JS散点图所需的格式)绘制散点图。

render_template('chart.html',data2 = data2)

当我使用jinja变量{{data2}}手动创建数据集时,以下代码有效

var chartData = {
        datasets : [{
            label: 'Cluster 1',
            fill: false,
            showLine: false,
            lineTension: 0.1,
            backgroundColor: "green",
            borderColor: "black", // The main line color
            borderCapStyle: 'square',
            borderDash: [], // try [5, 15] for instance
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "green",
            pointBackgroundColor: "green",
            pointBorderWidth: 1,
            pointHoverRadius: 8,
            pointHoverBackgroundColor: "yellow",
            pointHoverBorderColor: "brown",
            pointHoverBorderWidth: 2,
            pointRadius: 4,
            pointHitRadius: 10,
            // notice the gap in the data and the spanGaps: true
            data :{{data2[0]}},
            spanGaps: true,
        },
        {
            label: 'Cluster 2',
            fill: false,
            showLine: false,
            lineTension: 0.1,
            backgroundColor: "blue",
            borderColor: "black", // The main line color
            borderCapStyle: 'square',
            borderDash: [], // try [5, 15] for instance
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "blue",
            pointBackgroundColor: "blue",
            pointBorderWidth: 1,
            pointHoverRadius: 8,
            pointHoverBackgroundColor: "yellow",
            pointHoverBorderColor: "brown",
            pointHoverBorderWidth: 2,
            pointRadius: 4,
            pointHitRadius: 10,
            // notice the gap in the data and the spanGaps: true
            data :{{data2[1]}},
            spanGaps: true,
        },
        {
            label: 'Cluster 3',
            fill: false,
            showLine: false,
            lineTension: 0.1,
            backgroundColor: "red",
            borderColor: "black", // The main line color
            borderCapStyle: 'square',
            borderDash: [], // try [5, 15] for instance
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "red",
            pointBackgroundColor: "red",
            pointBorderWidth: 1,
            pointHoverRadius: 8,
            pointHoverBackgroundColor: "yellow",
            pointHoverBorderColor: "brown",
            pointHoverBorderWidth: 2,
            pointRadius: 4,
            pointHitRadius: 10,
            // notice the gap in the data and the spanGaps: true
            data :{{data2[2]}},
            spanGaps: true,
        },.....so on

 // get chart canvas
      var holder = document.getElementById("myChart2");
      var ctx = document.getElementById("myChart2").getContext("2d");

      // create the chart using the chart canvas
      var myChart = new Chart(ctx, {
        type: 'scatter',
        data: chartData,
        options: {
          scales: {
            xAxes: [{
              display: true,
              ticks: {
                beginAtZero: true,
                autoSkip: true,
                autoSkipPadding: 30,
                stepSize: 500,
                maxTicksLimit: 10        
              },
              scaleLabel: {
                display: true,
                labelString: 'Days',
                fontStyle: 'bold'
              }      
            }],
            yAxes: [{
              display: true,
              scaleLabel: {
                display: true,
                labelString: 'Oil Rate',
                fontStyle: 'bold'
              }
            }]
          }
        }
      });

但是当我使用tojson并在for循环中使用相同的变量时,它的不起作用(呈现空白图表)

var ds = []    
var d2 = {{data2|tojson}}
      for (var j=0; j < {{o}}; j++){
      ds.push ({
            label: 'Cluster' +j,
            fill: false,
            showLine: false,
            lineTension: 0.1,
            backgroundColor: colorlist[j],
            borderColor: colorlist[j], // The main line color
            borderCapStyle: 'square',
            borderDash: [], // try [5, 15] for instance
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "green",
            pointBackgroundColor: "green",
            pointBorderWidth: 1,
            pointHoverRadius: 8,
            pointHoverBackgroundColor: "yellow",
            pointHoverBorderColor: "brown",
            pointHoverBorderWidth: 2,
            pointRadius: 4,
            pointHitRadius: 10,
            // notice the gap in the data and the spanGaps: true
            data :d2[j],
            spanGaps: true,
        });
        }     
      var chartData2 = {
        datasets : ds
       }

      var holder = document.getElementById("myChart2");
      var ctx = document.getElementById("myChart2").getContext("2d");

      // create the chart using the chart canvas
      var myChart2 = new Chart(ctx, {
        type: 'scatter',
        data: chartData2,
        options: {
          scales: {
            xAxes: [{
              display: true,
              ticks: {
                beginAtZero: true,
                autoSkip: true,
                autoSkipPadding: 30,
                stepSize: 500,
                maxTicksLimit: 10        
              },
              scaleLabel: {
                display: true,
                labelString: 'Days',
                fontStyle: 'bold'
              }      
            }],
            yAxes: [{
              display: true,
              scaleLabel: {
                display: true,
                labelString: 'Oil Rate',
                fontStyle: 'bold'
              }
            }]
          }
        }
      });

为了更加清楚,这是为散点图js创建我的data2的方式:

x2 = {}
y2 = {}
data = {}
for i in n:
   x2[i] = list(df_no_anamolies['Days'[df_no_anamolies["clusters_oilvsDays"]==i])
   y2[i] = list(df_no_anamolies['Oil_rate(stb/d)'[df_no_anamolies["clusters_oilvsDays"]==i])
   T = []
   for j,k in zip(x2[i],y2[i]):
      T.append({'x': j, 'y': k})
   data[i] = str(T).replace('\'', '')
dt2 = list(data.items())
data2 = []
for i in range(len(dt2)):
    data2.append(dt2[i][1])

我的data2如下所示:

['[{x: 429, y: 21862.782000000003}, {x: 430, y: 21769.1868}]', 
 '[{x: 431, y: 21752.5183}, {x: 432, y: 21406.0022}]', 
 '[{x: 433, y: 20823.7369},'[{x: 434, y: 21101.5033}]', 
 '[{x: 435, y: 22031.354}, {x: 434, y: 21101.5033}]'....]

有人可以帮我做一个循环吗。

2 个答案:

答案 0 :(得分:0)

我认为您需要先解析这些json字符串,然后再将其传递给chart.js

var chartData2 = {
        datasets : [{label: 'Cluster 1',
            fill: false,
            showLine: false,
            lineTension: 0.1,
            backgroundColor: "green",
            borderColor: "black",
            borderCapStyle: 'square',
            borderDash: [], 
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "green",
            pointBackgroundColor: "green",
            pointBorderWidth: 1,
            pointHoverRadius: 8,
            pointHoverBackgroundColor: "yellow",
            pointHoverBorderColor: "brown",
            pointHoverBorderWidth: 2,
            pointRadius: 4,
            pointHitRadius: 10,
            data : JSON.parse( {{ data[1] }} ),
            spanGaps: true,
       }]      
}

答案 1 :(得分:0)

您的“ Y”对象是Decimal对象,并且JsonEnconder不接受Decimal对象。我通常只创建json.JSONEncoder的子类。

class DecimalEncoder(json.JSONEncoder):
    def _iterencode(self, o, markers=None):
        if isinstance(o, decimal.Decimal):
            return (str(o) for o in [o])
        return super(DecimalEncoder, self)._iterencode(o, markers)

然后您可以将其用作

json.dumps({'Y':decimal.Decimal('21769.1868')},cls = DecimalEncoder)