簡體   English   中英

帶有 JSON 列表變量的 ChartJS 散點圖不起作用

[英]ChartJS Scatter plot with JSON list variable not working

我想從我從 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'
              }
            }]
          }
        }
      });

為了更清楚,這是我的 data2 是如何為散點圖 js 創建的:

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}]'....]

有人可以幫助我如何用循環來做到這一點。

我認為你需要在將它們傳遞給 chart.js 之前解析這些 json 字符串

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,
       }]      
}

您的“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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM