我是D3.js的初学者。我想在D3js中使用Dynamic JSON创建一个简单的折线图。由于某种原因,我无法正确解析JSON并且轴未正确更新。以下是我的代码:
<html>
<head>
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #777;
shape-rendering: crispEdges;
}
.axis text
{
font-family: 'Arial';
font-size: 13px;
}
.tick
{
stroke-dasharray: 1,2;
}
.bar
{
fill: FireBrick;
}
</style>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
d3.xhr("http://104.131.191.213/books/", "application/json", function (error, data) {
if (error) return console.warn(error);
d = JSON.parse(data.response);
d = d3.entries(d);
d.forEach(function(d1){
d1.value.forEach(function(d) {
d.year = +d.year;
d.buys = +d.buys;
var vis=d3.select ("#visualisation"),
width=1000,
height=500,
MARGINS={top:20,right:20,bottom:20,left:50},
xRange = d3.time.scale()
.range([MARGINS.left, width - MARGINS.right])
.domain([d3.min(data, function(d) { return d.year; }),
d3.max(data,function(d) { return d.year; })]),
yRange = d3.scale.linear()
.range([height - MARGINS.top, MARGINS.bottom])
.domain([d3.min(data,function(d){
return d.buys; }),
d3.max(data, function(d) {
return d.buys; })]),
xAxis = d3.svg.axis()
.scale(xRange)
.tickSize(5)
.tickSubdivide(true),
yAxis = d3.svg.axis()
.scale(yRange)
.tickSize(5)
.orient("left")
.tickSubdivide(true);
vis.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0, " + (height - MARGINS.bottom) + ")")
.call(xAxis);
vis.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
var lineFunc = d3.svg.line()
.x(function(d) { return xRange(d.year); })
.y(function(d) { return yRange(d.buys); })
.interpolate('linear');
vis.append("svg:path")
.attr("d", lineFunc(data))
.attr("stroke","blue")
.attr("stroke-width",2)
.attr("fill","none");
});
});
})
</script>
</head>
<body>
<svg id="Visualisation" width="1000" height="500"> </svg>
</body>
</html>
下面的JSON:
{
"data": [
{
"buys": 5841,
"year": "1986"
},
{
"buys": 54,
"year": "1954"
},
{
"buys": 176,
"year": "1967"
},
{
"buys": 9389,
"year": "1991"
},
{
"buys": 63,
"year": "1953"
},
{
"buys": 1,
"year": "1910"
},
{
"buys": 3,
"year": "2006"
}
]
}