Javascript D3js,如何基于轴值(而非像素)设置点

Javascript D3js,如何基于轴值(而非像素)设置点,javascript,d3.js,svg,Javascript,D3.js,Svg,我有这样的情节。我用像素来放置点 让svg=d3.选择(“svg”), 宽度=+svg.attr(“宽度”), 高度=+svg.attr(“高度”), x=d3.scaleLinear().domain([20,20000]).range([0,width]), y=d3.scaleLinear().domain([-18,18]).range([height,0]),范围, axisBottom=d3.axisBottom(x), Axisleet=d3.Axisleet(x), 点数=[[

我有这样的情节。我用像素来放置点

让svg=d3.选择(“svg”),
宽度=+svg.attr(“宽度”),
高度=+svg.attr(“高度”),
x=d3.scaleLinear().domain([20,20000]).range([0,width]),
y=d3.scaleLinear().domain([-18,18]).range([height,0]),范围,
axisBottom=d3.axisBottom(x),
Axisleet=d3.Axisleet(x),
点数=[[100100],[300200],
环磷酰胺=10;
//如果我有如下数据,如何设置点
//点=[[5,6000],-10,18500]],不是像素而是轴单位
append('g')
.attr('class','axis--x')
.attr('transform','translate(0',+高度/2+'))
.呼叫(底部);
append('g')
.attr('class','axis--y')
.调用(d3.左(y));
让groupForCircles=svg.append('g').attr('id','groupForCircles')
积分。forEach(e=>{
groupForCircles.append(“g”)
.附加(“圆圈”)
.attr(“cx”,e[0])
.attr(“cy”,高度/2)
.attr(“r”,circleRadius)
.style(“填充”、“紫色”)
})
svg{
边框:1px实心#ccc;
显示:块;
保证金:自动;
溢出:可见;
边缘顶部:25px;
}

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');
完整演示:

让svg=d3.选择(“svg”),
宽度=+svg.attr(“宽度”),
高度=+svg.attr(“高度”),
x=d3.scaleLinear().domain([20,20000]).range([0,width]),
y=d3.scaleLinear().domain([-18,18]).range([height,0]),范围,
axisBottom=d3.axisBottom(x),
Axisleet=d3.Axisleet(x),
点数=[[100100],[300200],
moreData=[[56000]、-1018500]、[22000]、-18100],
环磷酰胺=10;
//如果我有如下数据,如何设置点
//点=[[5,6000],-10,18500]],不是像素而是轴单位
append('g')
.attr('class','axis--x')
.attr('transform','translate(0',+高度/2+'))
.呼叫(底部);
append('g')
.attr('class','axis--y')
.调用(d3.左(y));
让groupForCircles=svg.append('g').attr('id','groupForCircles')
积分。forEach(e=>{
groupForCircles.append(“g”)
.附加(“圆圈”)
.attr(“cx”,e[0])
.attr(“cy”,高度/2)
.attr(“r”,circleRadius)
.style(“填充”、“紫色”)
})
groupForCircles.selectAll(“.dataPoint”)
.数据(更多数据)
.输入()
.append('圆')
.classed('dataPoint',true)
.attr('cx',d=>x(d[1]))
.attr('cy',d=>y(d[0]))
.attr('r',4)
.style('fill','deepskyblue')
svg{
边框:1px实心#ccc;
显示:块;
保证金:自动;
溢出:可见;
边缘顶部:25px;
}

谢谢你,你救了我一天!