【问题标题】:setting uneven tick stepsize spacing with chart.js使用 chart.js 设置不均匀的刻度步长间距
【发布时间】:2019-02-24 21:29:27
【问题描述】:

我正在尝试使用charts.js 实现这样的目标:

我想要的是每个刻度都处于特定位置,而不是均匀分布在轴上。我已经通过根据索引有条件地将刻度颜色设置为红色或透明来实现上述目标。类似这样:

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是否提供更简单的解决方案

【问题讨论】:

    标签: javascript charts chart.js


    【解决方案1】:

    我一直在寻找类似问题的答案,最后我得到了以下 hack,它不一定比你的更好 :-)

    小提琴链接: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)');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多