我正在尝试使用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
我相信我正在以错误的方式加载数据。我该如何解决这个问题?
由于
答案 0 :(得分:0)
这可能会对您有所帮助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>