繁体   English   中英

d3js-使用json数据

[英]d3js - use json data

我正在尝试使用json数组在图表上添加一些线,如下所示:

var post_hours = [
  {
    location: 'SF',
    hour: 4,
    value: 30539
  },
  {
    location: 'NYC',
    hour: 8,
    value: 26119
  },
  {
    location: 'SF',
    hour: 17,
    value: 74840
  },
  {
    location: 'SF',
    hour: 21,
    value: 58000
  },
];

我使用以下代码:

svg.selectAll('line')
  .data(post_hours).enter()
  .append('line')
  .attr("class", "timezone-label")
  .transition()
  .delay(800)
  .duration(300)
  .attr({
      x1: x(function(d){ return d.hour; }), // here is where I get the error
      y1: height, 
      x2: x(function(d){ return d.hour; }), 
      y2: y(function(d){ return d.value; }) 
  })
  .style("stroke-dasharray", ("10, 5"))
  .style("opacity", 1)

但是我收到以下错误:

  Uncaught ReferenceError: d is not defined 

我相信我以错误的方式加载数据。 我怎样才能解决这个问题?

谢谢

这可以帮助您jsfiddle.ans

<!DOCTYPE html>
 <html>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>

var post_hours = [
{
location: 'SF',
hour: 4,
value: 30539
},
{
location: 'NYC',
hour: 8,
value: 26119
},
{
location: 'SF',
hour: 17,
value: 74840
},
{
location: 'SF',
hour: 21,
value: 58000
}
];

var domainOnlyScale =  d3.scale.linear().domain([0,10000]).range([0,200]);


var svg = d3.select("body").append("svg")
                         .attr("width",200)
                         .attr("height",200);

var height = 500;

var lineD = svg.selectAll("line")
                        .data(post_hours)
                        .enter()
                        .append("line");

var line = d3.svg.line()
            .x(function(d, i) {
                return d.hour;
            })
            .y(function(d, i) {
                return domainOnlyScale(d.value);
            }); 

  var displayline = lineD.attr("class", "timezone-label")
                        .transition()
                        .delay(200)
                        .duration(300)
                        .attr("x1", function(d){ return line(d);})
                        .attr("y1",function(d){ return height;})
                        .attr("x2", function(d){ return line(d);})
                        .attr("y2", function(d){ return line(d);})
                        .style("stroke-dasharray", ("10, 5"))
                        .attr("stroke", "red")
                        .attr("stroke-width", 30)
                        .style("opacity", 1);

   </script>
   </body>
   </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM