Cybernetic
Cybernetic

Reputation: 13354

Calculate the height in pixels that corresponds to a value on the axis of D3 graph

I have a D3 bar chart as follows:

enter image description here

I want to color the bars that pass the horizontal line the color green. I can do this as follows:

.attr("fill", function(d) { return (d.the_value > 0.65 ? "green" : "orange"); })

which works great. But the height of the horizontal bar itself is set using the height of the plot.

    svg.append("line")         
    .style("stroke", "black")  
    .attr("x1", 0)     
    .attr("y1", height/2)    
    .attr("x2", 600)
    .attr("y2", height/2);

I want to set the height of the horizontal bar by using the value 0.65. How can I get the height in pixels that corresponds to 0.65 on the axis?

Upvotes: 0

Views: 124

Answers (1)

meetamit
meetamit

Reputation: 25177

I presume you have something in your code like

yScale = d3.scale()
  .domain(...)
  .range([0, 600])

and that you use it to size and position the bars.

With that scale you can get the y-coordinate you're after using yScale(0.65). I.e.:

svg.append("line")         
.style("stroke", "black")  
.attr("x1", 0)     
.attr("y1", yScale(0.65))    
.attr("x2", 600)
.attr("y2", yScale(0.65));

Upvotes: 1

Related Questions