如何根据下拉列表更新 Chart.js?

2022-01-22 00:00:00 charts php laravel ajax chart.js

更新

我在我的图表中添加了一个下拉菜单,它允许用户在可用的操作员名称中进行选择.我需要您的帮助,以便在选择可用的操作员名称时,更新图形,仅显示所选操作员的信息.

I have added a dropdown to my chart which allows the user to select among the available operator names. I need your help so that when selecting an available operator name, the graphic is updated showing only the information of the selected operator.

从我所有的 JSON 响应中,对于这个例子,它应该只在红色框中显示信息:

From all my JSON response, for this example it should only show the information in a red box:

正如您在图片中看到的,如果我选择 Luis 操作员,此图表应该会更新并只显示 Luis 操作员(他有 2 个工作订单处于完成状态).

As you can see in the image, if I select the Luis operator, this graph should update and show me only the Luis operator (he has 2 work orders in finished state).

在我用来制作图表的report.js 文件下方.

getChartData() 方法:

我使用 ajax,基本上我正在获取数据并使用可用运算符的名称加载我的选择.

I use ajax, basically I'm getting the data and loading my select with the names of the available operators.

renderChart() 方法:我用这些参数将它作为参数标签和数据"传递我可以制作我的图表我还配置了一些可用的选项.

renderChart () method:   I am passing it as a parameter "label and data" with these parameters I can make my graph also I am configuring some available options.

select.on('change', function():

这里我不明白如何根据所选选项告诉我的图表更新,然后我必须再次调用 renderChart 方法以再次使用所选数据绘制图表,但它不起作用,我不知道如何解决它,这是我正在尝试的.

report.js

function getChartData(user) {    
    $.ajax({
         url: '/admin/reports/getChart/' + user,
        type: 'GET',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
        dataType: 'json',
        success: function (response) {             
            console.log(response);
            var data = [];
            var labels = [];         

            for (var i in response.orders) {

                data.push(response.orders[i].orders_by_user);
                labels.push(response.orders[i].name);  
                $("#operator").append('<option value='+response.orders[i].id+'>'+response.orders[i].name+'</option>');    
            }   
            renderChart(data, labels);              
        },

        error: function (response) {        
            console.log(response);
        }
    });
}

function renderChart(data, labels) {
    var ctx = document.getElementById("orders").getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Terminadas',
                data: data,
                borderColor: 'rgba(75, 192, 192, 1)',
                backgroundColor: "#229954",
                borderWidth: 1,
                yAxisID: 'Ordenes',
                xAxisID: 'Operarios',
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    id: "Ordenes",
                    ticks: {
                        beginAtZero: true

                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'Ordenes'
                    }
                }],
                xAxes: [{
                    id: "Operarios",
                    scaleLabel: {
                        display: true,
                        labelString: 'Operarios'
                    }

                }],
            },
            title: {
                display: true,
                text: "Ordenes en estado terminado"
            },
            legend: {
                display: true,
                position: 'bottom',
                labels: {
                  fontColor: "#17202A",
                }
            },
        }
    });

    function updateChart() {       
        myChart.destroy();     
        myChart = new Chart(ctx, {
            type: document.getElementById("operator").value,
            data: data
        });
    };

}

getChartData();

$('#operator').select2({
    placeholder: 'Selecciona un operario',
    tags: false              
});


 var select = $('#operator'); 
 var pElem = document.getElementById('p')           

   select.on('change', function() {                
     var item = $(this).val();               
     pElem.innerHTML = 'selectedValue: ' + item;
     var data = {
        labels: labels,
        datasets: data
     }
     var ctx = document.getElementById("orders").getContext('2d');
     var myChart = new Chart(ctx, {
          type: 'line',
          data: data
        });
 }); 

我的选择:

<select class="form-control" name="operator" id="operator">
    <option></option>                                                            
</select> 

我在尝试链接所选选项和要显示的信息时迷路了(更新图表).你能告诉我如何解决这个问题吗?

更新 1

我的选择:

<select class="form-control" name="operator" id="operator">
    <option></option>                                                            
</select> 

通过 ajax 我加载我的选择选项:

 for (var i in response.orders) {

   order.push(response.orders[i].orders_by_user);
   user.push(response.orders[i].name);              
   $("#operator").append('<option value='+response.orders[i].id+'>'+response.orders[i].name+'</option>');
 }      
 renderChart(order, user); 

有了你给我的答案,修改我的report.js文件正是我的function renderChart(order, user),如下:

With the answer you have given me, modify my report.js file exactly my function renderChart(order, user) and it is as follows:

function renderChart(order, user) {
    var ctx = document.getElementById("orders").getContext('2d');
    var myChart = new Chart(ctx, {
      //code...
    }); 

    //my select
    var selectOption = $('#operator');                    
    selectOption.on('change', function() {  

        var option = $("#operator").val();
        myChart.data.labels = option;
        if (option == 'All') {
           myChart.data.labels = user,
           myChart.data.datasets[0].data = order;
        } else {
          myChart.data.labels = option;
          myChart.data.datasets[0].data = order;
        }
        myChart.update();
    });            

}

图表更新不正确,出现错误,您可以在图片中看到:

显然,如果我选择全部"选项,它会正确显示和绘制图表,现在如果我选择jose",则会发生以下情况:

Obviously if I select the "All" option, it shows and graphs correctly, now if I select "jose" the following happens:

图表不尊重规模,我知道Jose只有1个工单,规模上最多2个.

在 x 轴上,在这种情况下,Jose"不是向我显示名称,而是向我显示选择 id,在这种情况下为 6.

米格尔"选项也是如此.

请帮我更正这部分:

var selectOption = $('#operator');                    
    selectOption.on('change', function() {  

        var option = $("#operator").val();
        myChart.data.labels = option;
        if (option == 'All') {
           myChart.data.labels = user,
           myChart.data.datasets[0].data = order;
        } else {
          myChart.data.labels = option;
          myChart.data.datasets[0].data = order;
        }
        myChart.update();
    });

推荐答案

当所选选项更改时,您不得销毁图表.您需要做的就是执行以下步骤.

When the selected options changes, you must not destroy the chart. All you need to do is performing the following steps.

  1. 更改data.labels
  2. 更改唯一数据集的data
  3. 更新图表本身

这基本上是这样完成的.

This is basically done as follows.

myChart.data.labels = <new labels>;
myChart.data.datasets[0].data = <new values>;
myChart.update();

以下示例说明了如何在 JavaScript 中完成此操作.

The following example illustrates how this can be done in JavaScript.

orders = [
  { name: 'Luis', orders_by_user: '2' },
  { name: 'Jose', orders_by_user: '1' },
  { name: 'Miguel', orders_by_user: '3' }
];

const myChart = new Chart(document.getElementById('orders'), {
  type: 'bar',
  data: {
    labels: orders.map(o => o.name),
    datasets: [{
      label: 'Terminadas',
      data: orders.map(o => o.orders_by_user),
      borderColor: 'rgba(75, 192, 192, 1)',
      backgroundColor: "#229954",
      borderWidth: 1,
      yAxisID: 'Ordenes',
      xAxisID: 'Operarios',
    }]
  },
  options: {
    scales: {
      yAxes: [{
        id: "Ordenes",
        ticks: {
          beginAtZero: true,
          stepSize: 1
        },
        scaleLabel: {
          display: true,
          labelString: 'Ordenes'
        }
      }],
      xAxes: [{
        id: "Operarios",
        scaleLabel: {
          display: true,
          labelString: 'Operarios'
        }

      }],
    },
    title: {
      display: true,
      text: "Ordenes en estado terminado"
    },
    legend: {
      display: true,
      position: 'bottom',
      labels: {
        fontColor: "#17202A",
      }
    },
  }
});

orders.forEach(o => {
  const opt = document.createElement('option');
  opt.value = o.name;
  opt.appendChild(document.createTextNode(o.name));
  document.getElementById('operator').appendChild(opt);
});

function refreshChart(name) {
  myChart.data.labels = [name];
  if (name == 'All') {
     myChart.data.labels = orders.map(o => o.name),
     myChart.data.datasets[0].data = orders.map(o => o.orders_by_user);
  } else {
    myChart.data.labels = [name];
    myChart.data.datasets[0].data = orders.find(o => o.name == name).orders_by_user;
  }
  myChart.update();
}

Operarios:
<select id="operator" onchange="refreshChart(this.value)">
    <option>All</option>                                                            
</select> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="orders" height="90"></canvas>

相关文章