Quantcast
Channel: User i alarmed alien - Stack Overflow
Viewing all articles
Browse latest Browse all 42

Answer by i alarmed alien for D3js, how set points based on axis values (not pixels)

$
0
0

The x and y scales are used to convert your values to the appropriate chart coordinates. To add your coordinates, you just need to use the scales that you have created to generate the correct x and y coordinates:

groupForCircles  .append('circle')  .attr('cx', d => x(d[0]) ) // `x` is your x scale, `y` is the y scale  .attr('cy', d => y(d[1]) )

It looks like you have got the x and y values switched around in your suggested data points, so I have altered the code slightly to account for that. I've also used standard d3 data binding to facilitate addition and manipulation of the points, rather than a forEach loop:

const moreData = [ [5, 6000], [-10, 18500], [2, 2000], [-18, 100] ]groupForCircles.selectAll('.dataPoint')  .data(moreData)             // bind the data .enter()                     // this is the new data being added to the chart .append('circle')            // add a circle element for each data element  .classed('dataPoint', true)  .attr('cx', d => x(d[1]) )  // use the second of the pair as the x coordinate  .attr('cy', d => y(d[0]) )  // and the first as the y  .attr('r', 4)  .style('fill', 'deepskyblue');

Full demo:

let svg = d3.select("svg"),    width = +svg.attr("width"),    height = +svg.attr("height"),    x = d3.scaleLinear().domain([20 , 20000]).range([0, width]),    y = d3.scaleLinear().domain([-18 , 18]).range([height, 0]),    axisBottom = d3.axisBottom(x),    axisLeft =  d3.axisLeft(x),    points =[[100, 100], [300, 200]],    moreData = [ [5, 6000], [-10, 18500], [2, 2000], [-18, 100] ],    circleRadius = 10;    // How can I set points if I have data like// points =[[5, 6000], [-10, 18500]], not pixels but axis unitssvg.append('g')    .attr('class', 'axis axis--x')    .attr('transform', 'translate(0,'+ height/2 +')')    .call(axisBottom);svg.append('g')        .attr('class', 'axis axis--y')        .call(d3.axisLeft(y));let groupForCircles = svg.append('g').attr('id', 'groupForCircles')points.forEach(e => {    groupForCircles.append("g")        .append("circle")        .attr("cx", e[0])        .attr("cy", height/2)        .attr("r", circleRadius)        .style("fill", "purple")})groupForCircles.selectAll('.dataPoint')  .data(moreData)  .enter() .append('circle')  .classed('dataPoint', true)  .attr('cx', d => x(d[1]) )  .attr('cy', d => y(d[0]) )  .attr('r', 4)  .style('fill', 'deepskyblue');
svg {          border: 1px solid #ccc;          display: block;          margin: auto;          overflow: visible;          margin-top: 25px;      }
<script src="https://d3js.org/d3.v5.min.js"></script><svg width="500" height="300"></svg>

Viewing all articles
Browse latest Browse all 42

Trending Articles