Michael Richter Michael Richter -4 years ago 111
Javascript Question

d3 get x, y values on click

I am trying to get the x, y values on a mouse click. I am successfully getting these values, but they are within the width and height of my chart and not the actual x and y axis values. The chart has a width of 600, and a height of 200. I am getting the click point using:

var m = d3.mouse(this);
console.log(m);


The log values are is x, y (x of 0-600, y of 0-200). For example, a click could return -- 420, 120

How do I get the x and y axis values (date and integer values) from this click?

Answer Source

You can retrieve co-ordinates as follows Hope, this is what you want. Check this click code

    d3.select('body').on('click', function(){
  log('msg is'+  xScale.invert(d3.event.pageX));
})

JSFIDDLE

var w = 500;
var h = 100;
var dataset = [
    [5, 20],
    [480, 90],
    [250, 50],
    [100, 33],
    [330, 95],
    [410, 12],
    [475, 44],
    [25, 67],
    [85, 21],
    [220, 88]
];

var xScale = d3.scale.linear()
    .domain([0, d3.max(dataset, function (d) {
    return d[0];
})])
    .range([0, w]);

var yScale = d3.scale.linear()
    .domain([0, d3.max(dataset, function (d) {
    return d[1];
})])
    .range([0, h]);

var svg = d3.select("body")
    .append("svg")
    .attr("width", w)
    .attr("height", h);
svg.selectAll("circle")
    .data(dataset)
    .enter()
    .append("circle")
    .attr("cx", function (d) {
    return xScale(d[0]);
})
    .attr("cy", function (d) {
    return yScale(d[1]);
})
    .attr("r", function (d) {
    return Math.sqrt(h - d[1]);
}).on('click', function(d,i){
  log('x is '+ d[0] + 'y is '+ d[1]);  
 
});
d3.select('body').on('click', function(){
  log('msg is'+  xScale.invert(d3.event.pageX));
})
function log(msg){
   
 d3.select('#selected').html('<hr>' + '<br>' +msg + '<hr>');   
}
svg.selectAll("text")
    .data(dataset)
    .enter()
    .append("text")
    .text(function (d) {
    return d[0] + "," + d[1];
})
    .attr("x", function (d) {
    return d[0];
})
    .attr("y", function (d) {
    return d[1];
})
    .attr("font-family", "sans-serif")
    .attr("font-size", "11px")
    .attr("fill", "red")
;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="selected"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download