Bongowen Bongowen - 7 days ago 5
Javascript Question

How to highlight single y-axis grid line

I am looking for way to highlight a single grid line on the y-axis of a plotly chart.

enter image description here

Example: In the upper chart the 100K line should be thicker and in different color!

As I always want to highlight a grid line of a special y-axis value it may be easier to draw a separate line for a given y-value. Is there a simple way to do this?

Answer

You can select the horizontal tick lines by their class and index and then change their style.

Plotly.d3.selectAll('.ygrid').filter('.crisp').filter(function(d,i) {return i==1})

The class of the horizontal tick lines is ygrid crisp and their index starts at 0, i.e. the first line after the x-axis.

It will work when you have a fixed number of tick lines and a fixed range, otherwise you will always highlight a different line.

For a more robust approach, have a look at the 2nd snippet.

var data = [{
  x: ['giraffes', 'orangutans', 'monkeys'],
  y: [50, 14, 33],
  type: 'bar'
}];

Plotly.newPlot('myDiv', data);

var line = Plotly.d3.selectAll('.ygrid').filter('.crisp').filter(function(d,i) {return i==1})
line.style("stroke", "rgb(255,0,0)")
line.style("stroke-width", "10px")
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv" style="width: 480px; height: 400px;">


line_label defines the label next to the tick line which we want to highlight. We can use the fact that all tick labels have a corresponding tick line and the index are different by exactly one.

First we identify the tick label with the correct label, then use its index to identify the tick line and modify its style.

The snippet below produces random data with random tick labels and ticks lines, but the line for y == 20 is always highlighted.

var data = [{
  x: ['giraffes', 'orangutans', 'monkeys'],
  y: [Math.random()*100, 14, 33],
  type: 'bar'
}];

Plotly.newPlot('myDiv', data);

var line_label = '20';
var line_index = -1;
Plotly.d3.selectAll('.ytick').filter(function(d, i) {
    if (this.textContent == line_label) {
        line_index=i;
        return i;
    }
})

var line = Plotly.d3.selectAll('.ygrid').filter('.crisp').filter(function(d,i) {return i == line_index - 1})
line.style("stroke", "rgb(255,0,0)")
line.style("stroke-width", "10px")
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv" style="width: 480px; height: 400px;">