使用 Chart.js 的折线图

我有两个表,我在执行mysql查询(table1是pl_pl,table2是act_act)后得到的表格:


table1:


label   act_hrs

Jan-19  7

Feb-20  8

Mar-20  9


table2:

label   pl_hrs

Mar-20  45

Apr-20  53

我必须标记中的所有点act_hrs并pl_hrs使用具有共同 x 轴的折线图label 。我为此尝试了以下javascript代码:


javascript代码:


function show_scurve_Graph()

        {

            {

                var plandata = <?php echo json_encode($pl_pl); ?>;

                var actualdata = <?php echo json_encode($act_act); ?>;


                var labels = [];

                  for (var i in plandata) {

                        labels.push(plandata[i].label);

                  }

                  for (var j in actualdata) {

                        labels.push(actualdata[j].label);

                  }


                new Chart("scurve_chart", {

  type: 'line',

  data: {

    labels: Array.from(labels),

    datasets: [{

        label: "Planned Hours",

        fill: false,

        borderColor: "rgba(255, 0, 0, 1)",

        pointHoverBackgroundColor: "rgba(255, 0, 0, 1)",

        data: plandata.map(o => ({ x: Number(o.label), y: Number(o.pl_hrs)}))

      },

      {

        label: "Actual Hours",

        fill: false,

        backgroundColor: "rgba(0, 255, 0, 0.75)",

        borderColor: "rgba(0, 255, 0, 1)",

        pointHoverBackgroundColor: "rgba(0, 255, 0, 1)",

        pointHoverBorderColor: "rgba(0, 255, 0, 1)",

        data: actualdata.map(o => ({x: Number(o.label), y: Number(o.act_hrs)}))

      }

    ]

  },

  options: {    

    tooltips: {

      callbacks: {

        title: (tooltipItem, data) => "Month " + data.datasets[tooltipItem[0].datasetIndex].data[tooltipItem[0].index].x

      }

    },

    scales: {

      yAxes: [{

        ticks: {

          beginAtZero: true

        },

       scaleLabel: {

        display: true,

        labelString: 'Hours'

      }

      }],

      xAxes: [{

        ticks: {          

          min: 0,

          max: 53,

          stepSize: 1

        },

        scaleLabel: {

        display: true,

        labelString: 'Month'

      }

      }]

    }

  }

});

 }}



交互式爱情
浏览 177回答 1
1回答

莫回无

以下几行是罪魁祸首:data: plandata.map(o => ({ x: Number(o.label), y: Number(o.pl_hrs)}))和data: actualdata.map(o => ({x: Number(o.label), y: Number(o.act_hrs)}))map回调应该只返回小时数字,如下所示:// Planneddata: plandata.map(o => Number(o.pl_hrs))// Actualdata: actualdata.map(o => Number(o.act_hrs))该data属性只需要您要在图形上绘制的图形数组。这是一个jsfiddlelabels注意:您应该根据您在图表配置中使用的标签对所有数据源上的数据进行规范化。我的意思是,数据数组中数字的顺序应该与标签顺序相对应。
打开App,查看更多内容
随时随地看视频慕课网APP