使用chart.js设置不均匀的刻度线步距

时间:2018-06-28 14:22:50

标签: javascript charts chart.js

我正在尝试通过Charts.js实现类似的目标:

I'm trying to achieve something like this

我想要的是将每个刻度线都放置在特定位置,以使其均匀地分布在整个轴上。我设法通过根据其索引有条件地将刻度颜色设置为红色或透明来实现上述目的。与此类似:

const steps = [1,24, 54, 93]
const options = {
  scales: {
    yAxes: [{
      gridLines: {
        color: [...new Array(100)].map((x,i) => steps.includes(i) ? "rgba(255, 0, 0, 1)" : "rgba(255, 0, 0, 0)"),
      }
    }]
  }
}

但是,此解决方案感觉很hacky,我想知道Chartsjs是否提供了更简单的解决方案

1 个答案:

答案 0 :(得分:0)

我一直在寻找类似问题的答案,但最终还是遇到了以下黑客攻击,不一定比您的黑客更好:-)

链接到小提琴:https://jsfiddle.net/hdahle/obc4amfh/

var colors = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange']
var votes = [5, 6, 35, 76, 20, 10];

var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
  options: {
    responsive: true,
    legend: {
      display: false
    }
  },
  type: 'line',
  data: {
    labels: colors,
    datasets: [{
      label: 'Votes',
      data: votes,
      borderColor: 'rgba(30,150,60,0.8)',
      backgroundColor: 'rgba(30,150,60,0.3)',
      borderWidth: 1,
      fill: true,
    }]
  }
});

function drawHorizontalLine(value, color) {
  let d = [];
  for (let i = 0; i < myChart.data.labels.length; i++) {
    d.push(value)
  }
  myChart.data.datasets.push({
    data: d,
    pointRadius: 0,
    type: 'line',
    borderColor: color,
    borderWidth: 1,
    fill: false,
  });
  myChart.update();
}

drawHorizontalLine(76, 'rgba(175,40,50,0.6)');
drawHorizontalLine(44, 'rgba(175,40,50,0.6)');
drawHorizontalLine(21, 'rgba(175,40,50,0.6)');
drawHorizontalLine(12, 'rgba(175,40,50,0.6)');
drawHorizontalLine(3, 'rgba(175,40,50,0.6)');