Шкалы x и y используются для преобразования ваших значений в соответствующие координаты диаграммы.Чтобы добавить свои координаты, вам просто нужно использовать шкалы, которые вы создали, чтобы сгенерировать правильные координаты x и y:
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]) )
Похоже, вы переключили значения x и y в предложенных вами значениях.данные, поэтому я немного изменил код, чтобы учесть это.Я также использовал стандартную привязку данных d3 для облегчения добавления и манипулирования точками, а не цикл forEach
:
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');
Полная демонстрация:
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 units
svg.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>