单击交互式chart.js条形图并获取JS中标签和组的值

问题描述 投票:0回答:1

我正在构建一个Web应用程序,您可以在其中选择航空公司,并获得条形图,其中包含五个类别(公司,食品,行李,守时,员工)的得分。当用户单击图表的不同部分时,我想获得公司名称和类别的值。这是要使用公司名称和类别的值在Python中做进一步的工作。

例如,在下图中,当用户单击绿色大条(右侧第四个条)时,我希望我的JS收到company="Air France", category="punctuality"。我认为我需要对onclick做些事情,但无法弄清楚...

enter image description here

上下文:根据您在表单框中选择的公司,Python后端将json数据返回给JS。在JS中,addGroupBarChart使用Chart.js绘制图表并将其嵌入html的canvas元素中。

这是JavaScript的摘录

document.getElementById('button').onclick = function(){
/* returns the companies value chosen from the dropdown */
/* and draw a chart using addGroupBarChart function */
    let companies = $("#companies").val();
    let headers = new Headers()
    let init = {
        method : 'GET',
        headers : headers
    }
    let params = {
        'companies':companies
    }

    let url = getWebAppBackendUrl('/get_stats')+'/'+JSON.stringify(params)
    let promise = fetch(url, init) 
                   .then(function(response){
                       response.json()
                               .then(function(data){
                                addGroupBarChart(data.barChartGroup.company, 
                                                 data.barChartGroup.labels);
                                })
                   });
}


document.getElementById("bar-chart-group").onclick = function(......) {
/* returns the company and category chosen from the chart */
/* this is the function I don't know how to build */
    let activePoints = // here I assume I need getPointsAtEvent(evt) but not sure...
    let company = // company value based on the click on the chart
    let category = // category value based on the click on the chart
    let headers = new Headers()
    let init = {
        method : 'GET',
        headers : headers
    }
    let params = {
        'company':company,
        'category':category
    }

    let url = getWebAppBackendUrl('/get_table')+'/'+JSON.stringify(params)
    let promise = fetch(url, init) 
                   .then(function(response) {
                       response.json()
                       .then(function(data){
                           // function to add table
                       })
                   });
}


function addGroupBarChart(data, labels) {
/* function to add a bar chart using the data returned from Python backend */
    document.getElementById('bar-card').innerHTML = '<canvas id="bar-chart-group" chart-click="onClick"></canvas>';
    i = 1
    arr = []
    data.forEach(function(d){
        company = Object.keys(d);
        values = d[company]['data'];
        dataset_company = {
            label:company,
            backgroundColor: default_colors[i],
            data:values};
        console.log("dataset_company", dataset_company);
        arr.push(dataset_company);
        i+=1;
    })

    let data_grouped = {
        labels: labels,
        datasets: arr
              };

    new Chart(document.getElementById("bar-chart-group"), {
        type: "bar",
        data: data_grouped,
        options: {
          title: {
            display: false,
            text: "Sentiment by category"
          }
        }
    });
}

datalabels进入addGroupBarChart的参数看起来像

data = [{"Air France":{"data":[0.1, -0.2, 0.3, -0.1, 0.1]}}, 
        {"Lufthansa":{"data":[0.3, -0.2, 0.5, 0.2, 0.1]}}]

labels = ["company", "food", "luggage", "punctuality", "staff"]

我尝试了包括this在内的几种解决方案,但是即使单击“显示图表”按钮,它也使我的应用程序不显示图表。我从上周开始学习JS,所以不算什么...任何帮助将不胜感激。谢谢!

javascript python onclick chart.js bar-chart
1个回答
0
投票

您可以定义一个onClick事件处理程序,但不幸的是,该文件没有很好的记录。在您的情况下,它看起来如下,onClick是您自己的函数,将使用onBarClickedcompany来调用。

category

请在下面查看您的修改后的代码:

options: {
  ...
  onClick: event => {
    const datasetIndex = chart.getElementAtEvent(event)[0]._datasetIndex;
    const model = chart.getElementsAtEvent(event)[datasetIndex]._model;
    onBarClicked(model.datasetLabel, model.label);
  }
}
function onBarClicked(company, category) {
  console.log('company = ' + company + ", category = " + category);
}

const default_colors = ['green', 'blue'];
function addGroupBarChart(data, labels) {
  arr = []
  data.forEach((d, i) => {
    company = Object.keys(d)[0];
    values = d[company]['data'];
    dataset_company = {
      label: company,
      backgroundColor: default_colors[i],
      data: values
    };
    arr.push(dataset_company);
  });

  let data_grouped = {
    labels: labels,
    datasets: arr
  };

  var chart = new Chart("bar-chart-group", {
    type: "bar",
    data: data_grouped,
    options: {
      title: {
        display: false,
        text: "Sentiment by category"
      },
      onClick: event => {
        const datasetIndex = chart.getElementAtEvent(event)[0]._datasetIndex;
        const model = chart.getElementsAtEvent(event)[datasetIndex]._model;
        onBarClicked(model.datasetLabel, model.label);
      }
    }
  });
}

const data = [{"Air France":{"data":[0.1, -0.2, 0.3, -0.1, 0.1]}}, 
        {"Lufthansa":{"data":[0.3, -0.2, 0.5, 0.2, 0.1]}}];
const labels = ["company", "food", "luggage", "punctuality", "staff"];
addGroupBarChart(data, labels);
© www.soinside.com 2019 - 2024. All rights reserved.