如何为每个x值绘制多个y值的散点图?

问题描述 投票:1回答:2

我有以下格式的数据,我想用d3绘制:

data = [
        { x: 0.2, y: [ 1, 2, 4 ] },
        { x: 0.3, y: [ 2 ] },
        { x: 0.5, y: [ 4, 7, 8, 12, 19 ] }
        { x: 1.4, y: [ 1, 3 ] }
       ]

通常,y轴值是整数,但这里它们是数组,因此以下代码不能按预期工作:

svg.selectAll("circle")
    .data(data)
    .enter()
    .append("circle")
        .attr("cx", function(d){ return x(d.x) })
        .attr("cy", function(d){ return y(d.y) })
        .attr("r", 2)

不是为数组中的每个值绘制多个圆,而是只获得一个。

此网站上的其他类似问题仅涉及具有固定数量的y轴值的数据,因此我没有找到针对此问题修改这些解决方案的方法。

javascript d3.js data-visualization visualization
2个回答
1
投票

这里传统的D3答案是为每个对象附加一个组,然后为每个组的每个y值附加一个圆。

但是,既然你似乎是一个D3初学者(如果我错了就纠正我),我建议只创建一个对象数组,你可以传递给data

有几种方法可以做到这一点,例如:

const newData = data.reduce(function(a, c) {
  return a.concat(c.y.map(function(d) {
    return {
      x: c.x,
      y: d
    }
  }));
}, []);

以下是您更改的代码:

const data = [{
    x: 0.2,
    y: [1, 2, 4]
  },
  {
    x: 0.3,
    y: [2]
  },
  {
    x: 0.5,
    y: [4, 7, 8, 12, 19]
  }, {
    x: 1.4,
    y: [1, 3]
  }
];

const newData = data.reduce(function(a, c) {
  return a.concat(c.y.map(function(d) {
    return {
      x: c.x,
      y: d
    }
  }));
}, []);

const x = d3.scaleLinear()
  .domain([0, 2])
  .range([0, 300]);

const y = d3.scaleLinear()
  .domain([0, 20])
  .range([0, 150]);

const svg = d3.select("svg");
svg.selectAll("circle")
  .data(newData)
  .enter()
  .append("circle")
  .attr("cx", function(d) {
    return x(d.x)
  })
  .attr("cy", function(d) {
    return y(d.y)
  })
  .attr("r", 4)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>

0
投票

为什么不尝试解开数据阵列呢?这应该很容易处理。

data = [{
    x: 0.2,
    y: [1, 2, 4]
  },
  {
    x: 0.3,
    y: [2]
  },
  {
    x: 0.5,
    y: [4, 7, 8, 12, 19],
  },
  {
    x: 1.4,
    y: [1, 3]
  }
];
unwrappedData = [];

for (b in data) {
  var temp = data[b].y.map((foo) => {
    return {
      x: data[b].x,
      y: foo
    }
  })
  unwrappedData = unwrappedData.concat(temp);

}

console.log(unwrappedData);

var svg = d3.select("body").append("svg")
  .attr("width", 100)
  .attr("height", 100)
  .style("margin-top", "58px");

svg.selectAll("circle")
  .data(unwrappedData)
  .enter()
  .append("circle")
  .attr("cx", function(d) {
    return d.x
  })
  .attr("cy", function(d) {
    return d.y
  })
  .attr("r", 2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

另外,cx和cy属性不应该返回d.xd.y吗?

© www.soinside.com 2019 - 2024. All rights reserved.