Plotly JavaScript: Customize y ticks or labels on y axis

3.2k views Asked by At

Iam using Plotly.js https://plotly.com/javascript/. I am trying to develop a chart where I want to add a small image on each ticks on the y axis. For reference please see the image given below.

enter image description here

Notice the small gray discs on y axis (next to the texts "Red", "Green" and "Blue"). I am trying to achieve something like this. However on the reference document, I couldn't find anything that does this.

How can I achieve that?

[UPDATE]
After implementing the answer as suggested by @Ruben, and further making some updates, I get this little tip of the x-axis extended to the left to the negative side (ref. the screenshot of this extended tip below)

enter image description here

1

There are 1 answers

4
Ruben Helsloot On BEST ANSWER

If it's really only about the dots, I've hacked together something that inserts this unicode shape as a solid, black circle at every bar using annotations. Then you can colour it if you want.

var data = [{
  type: 'bar',
  x: [20, 14, 23],
  y: ['giraffes', 'orangutans', 'monkeys'],
  orientation: 'h'
}];

var layout = {
  annotations: data[0].y.map((v, i) => ({
    x: -0.75,
    y: i,
    xref: 'x',
    yref: 'y',
    text: "⬤",
    showarrow: false,
    font: {
      size: 14,
      color: ['red', 'blue', 'green'][i % 3]
    }
  }))
};

Plotly.newPlot('myDiv', data, layout);
<script src='https://cdn.plot.ly/plotly-latest.js'></script>
<div id='myDiv'></div>


Edit: now using changed labels:

var data = [{
  type: 'bar',
  x: [20, 14, 23],
  y: ['giraffes', 'orangutans', 'monkeys'],
  orientation: 'h'
}];

data[0].y = data[0].y.map((v, i) => {
  const color = ['red', 'blue', 'green'][i % 3];
  return `${v} <span style="color: ${color};">&#11044;</span>`
})

var layout = {
  xaxis: {
    showline: true,
  },
  margin: {
    l: 100,
  }
};

Plotly.newPlot('myDiv', data, layout);
<script src='https://cdn.plot.ly/plotly-latest.js'></script>
<div id='myDiv'></div>