1

我正在使用 chart.js 绘制简单的折线图。我想在我的行中显示红色的点。例如,我传递了一个数组作为从 1 到 100 的数字数据集。我想将偶数点显示为红色。这在chart.js中是否可行。

我知道我可以遍历该数组并从该数组中取出偶数值,然后将该数组传递给数据集。你能在这方面帮忙吗?这是我的数据集代码

这是我的数据集

datasets: [
        {
            label: 'Assay Values',
            fill: false,
            lineTension: 0,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderWidth: 1,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 1,
            pointHitRadius: 10,
            data: data.assay_value,
            spanGaps: false
        },

data.assay_values 是包含数组的数组。

任何形式的帮助将不胜感激

4

1 回答 1

1

假设data.assay_values包含一个数字数组(例如[65, 59, 80, 81, 56, 55, 40]),并且您只希望图表显示偶数值,您可以使用下面的代码将数据数组处理成一个新数组,只保留偶数。

请记住,您还必须构建一个新labels数组,因为您的数据集数据数组必须与图表标签的长度相同(因为数据中的每个索引都映射到相应的标签索引)。

请注意,由于您没有labels在问题中提供有关数组的任何详细信息,因此此代码假定您有一个名为的数组labels,其中包含一个字符串数组。您将需要根据您在实施中定义标签的方式进行更改。

var evenData = [];
var newLabels = [];

data.assay_values.forEach(function(e, i) {
  // only take the even values
  if (e % 2 === 0) {
    evenData.push(e);
    newLabels.push(labels[i]);
  }
});

然后更改您的 chart.js 图表配置以使用您的新标签和数据数组,如下所示。

var data = {
  labels: newLabels,
  datasets: [{
    label: 'Assay Values',
    fill: false,
    lineTension: 0,
    backgroundColor: "rgba(75,192,192,0.4)",
    borderColor: "rgba(75,192,192,1)",
    borderCapStyle: 'butt',
    borderDash: [],
    borderDashOffset: 0.0,
    borderWidth: 1,
    borderJoinStyle: 'miter',
    pointBorderColor: "rgba(75,192,192,1)",
    pointBackgroundColor: "#fff",
    pointBorderWidth: 1,
    pointHoverRadius: 5,
    pointHoverBackgroundColor: "rgba(75,192,192,1)",
    pointHoverBorderColor: "rgba(220,220,220,1)",
    pointHoverBorderWidth: 2,
    pointRadius: 1,
    pointHitRadius: 10,
    data: evenData,
    spanGaps: false
  }]
};

// configure your chart options here
var options = {};

// ctx is a jQuery instance or 2d context of the canvas of where we want to draw the chart.
var myLineChart = new Chart(ctx, {
  type: 'line', 
  data: data, 
  options: options 
});
于 2017-03-10T12:17:59.030 回答