d3js +圈不包含在我的图表中

时间:2018-03-25 18:16:58

标签: javascript d3.js

我对d3js有疑问。我创建了一个宽度和高度的SVG,但是我只有1个圆圈,看看这个角度是否超出了SVG的高度。我不知道为什么。

这里是代码:

function fun1(){
var str='apple';
var charArray =str.split('');
return charArray;
}

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您需要使用已定义的比例。

svg.selectAll(".dot")
  .data(data)
.enter().append('circle')
  .attr("cx", function(d){return x(d.age)})
  .attr("cy", function(d){return y(d.score)})
  .attr("fill", "blue")
  .attr("r",3)

答案 1 :(得分:0)

You have two ways:

1- using the one Sina has explained, which is the quickest to do.

2- Doing a little bit of computation, which is a bit helpful to understand how d3 scaling works.

Here is the second approach:

var data = [{
    age: 10,
    score: 2000
  },
  {
    age: 50,
    score: 500
  },
  {
    age: 20,
    score: 500
  },
  {
    age: 45,
    score: 100
  },
  {
    age: 32,
    score: 1000
  },
  {
    age: 89,
    score: 552
  },
];


var margin = {
    top: 40,
    right: 40,
    bottom: 40,
    left: 40
  },
  width = 600 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append('g')
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")")

var x = d3.scaleLinear()
  .domain([0, d3.max(data, function(d) {
    return d.age;
  })])
  .range([0, width])

var y = d3.scaleLinear()
  .domain([0, d3.max(data, function(d) {
    return d.score;
  })])
  .range([height, 0])

var xAxis = d3.axisBottom()
  .scale(x);

var yAxis = d3.axisLeft()
  .scale(y);

svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append('g')
  .call(yAxis);

svg.selectAll(".dot")
  .data(data)
  .enter().append('circle')
  .attr("cx", function(d) {
    return (width / d3.max(data, function(d) {
      return d.age;
    })) * d.age
  })
  .attr("cy", function(d) {
    return (height / d3.max(data, function(d) {
      return d.score;
    })) * Math.abs(d.score - d3.max(data, function(d) {
      return d.score;
    }))
  })
  .attr("fill", "blue")
  .attr("r", 3)