2

I'm trying to achieve something like this with charts.js:

I'm trying to achieve something like this

What I want is for each tick to be in a specific position as apposed to being uniformly spread across an axis. I had managed to achieve the above by conditionally setting the tick color to red or transparent based on its index. Similar to 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)"),
      }
    }]
  }
}

However, this solution feels extremely hacky and I would like to know if chartsjs offers a simpler solution

Hello World
  • 1,102
  • 2
  • 15
  • 33

1 Answers1

0

I was looking for an answer to a similar problem, and I ended up with the following hack which isn't necessarily a better hack than yours :-)

Link to fiddle: 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)');
hdahle
  • 51
  • 5