javascript - 具有多个数据集的分组散点图 D3

标签 javascript jquery d3.js scatter-plot

目前我有 3 个数组形式的数据集,我想将其中一个数据集保留为 Y 轴,其余数据集绘制在散点图上并作为 X 轴范围。

到目前为止,我只能在 Y 轴上绘制一个数据集,在 X 轴上绘制一个数据集。

g.selectAll("scatter-dots")
  .data(y1data)
  .enter().append("svg:circle") 
  .attr("cy", function (d) { return y(d); } ) 
  .attr("cx", function (d,i) { return x(xdata[i]); } ) 

要绘制的数据集是 x1data x2data 作为 X 轴,以及 X 轴范围和域将如何变化

这是我当前的 X 轴

var x = d3.scale.linear()
          .domain([11, d3.max(x1data)])  //i am only taking the max of one dataset.
          .range([ 0, width ]);       

这三个数据集是

x1data= [11, 22, 10, 55, 44, 23, 12, 56, 100, 98, 75, 20]
x2data= [8, 41, 34, 67, 34, 13, 67, 45, 66, 3, 34, 75]
y1data = [2000, 2001, 2004, 2005, 2006,2007]

我想实现类似的散点图 This

最佳答案

不太确定是否要使用 x2 作为独立于 x 轴的第三个视觉变量,或者 x1 和 x2 连接在一起形成一个系列,但关键是任一情况下的 d3.zip 函数 - https://github.com/mbostock/d3/wiki/Arrays#d3_zip

<小时/>

要使用 x2 作为第三个变量,即圆半径,请使用 d3.zip 将三个数组转换为三元素数组的数组:

var data = d3.zip ([y1data, x1data, x2data]);

数据现在将为 [[2000,11,8],[2001,22,41], ... 等等 ...]。

然后在您的散点图选择上使用它

g.selectAll("scatter-dots")
  .data(data)
  .enter().append("svg:circle") 
  .attr("cy", function (d) { return y(d[0]); } ) // d[0] is the value from y1data for this datum
  .attr("cx", function (d,i) { return x(d[1]); } ) // d[1] is the value from x1data for this datum
  .attr("r", function (d,i) { return rscale(d[2]); } ) // d[2] is the value from x2data  for this datum.
  // ^^^rscale will need to be a scale you construct that controls the mapping of the x2 values
<小时/>

如果您想将 x1 和 x2 绘制为不同的系列,但两者都与 x 轴相关,请使用 d3.zip 执行此操作:

var data1 = d3.zip ([y1data, x1data, y1data.map (function(a) { return 1; }); ]);
var data2 = d3.zip ([y1data, x2data, y1data.map (function(a) { return 2; }); ]);
var data = data1.concat(data2);

数据现在将是 [[2000,11,1],[2001,22,1], ... 等等 ..., [2000,8,2], [2001,41,2], .. .等等...]。

g.selectAll("scatter-dots")
  .data(data)
  .enter().append("svg:circle") 
  .attr("cy", function (d) { return y(d[0]); } ) // d[0] is the value from y1data for this datum
  .attr("cx", function (d,i) { return x(d[1]); } ) // d[1] is the value from x1data or x2data for this datum
  .attr("r", "5") // fixed radius this time
  .attr("fill", function (d,i) { return colscale(d[2]); } ) // d[2] is either 1 or 2 for this datum
  // ^^^colscale will need to be a scale you construct that controls the mapping of the values 1 or 2 to a colour

关于javascript - 具有多个数据集的分组散点图 D3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37133502/

相关文章:

jQuery on() 委托(delegate)事件和 Leaflet.js

javascript - 将 SVG 线条元素添加到折线图中

javascript - 在 d3.js 中填充两个重叠区域

javascript - 如何在 React 网站中使用中型小部件

javascript - ReactJS 中的错误 "Assignment to constant variable"

javascript - flatMap 在 yarn 测试 JavaScript 中不起作用

javascript - 用 Javascript 或 jQuery 替换甚至更好地删除内联样式?

javascript - CalendarExtender 使用 Javascript 更改日期

javascript - 节目结束后将焦点设置为锚定在 div 内?

html - 如何在 D3 中添加 html 表单?