如何使用Json文件绘制折线图

How to plot line chart using Json File

本文关键字:绘制 折线图 文件 Json 何使用      更新时间:2023-09-26

我无法用json文件中的数据绘制折线图。请帮我哪里出错了!

我的代码是-http://jsfiddle.net/arnica04/UVe57

<!DOCTYPE html>
<meta charset="utf-8">
<title>Mean Zero Time Series</title>
<style>
/* line style */
    path {
    stroke: red;
    stroke-width: 2;
    fill: none; /* stop it being solid area */
}
/* x axis tick */
.x.axis line {
    stroke: #000;
}
    /* x axis line */
.x.axis path {
    fill: none;
    stroke: #000;
}
 /* Y tick */
.y.axis line, .y.axis path {
    fill: none;
    stroke: #000;
}
</style>
<div id="graph" class="aGraph" style="position:absolute;top:0px;left:0; float:left;">     
</div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
d3.json("data.json", function(error, data) {
    plotChart(data); //load the json data
});
function plotChart(data) {
    var w = 800; //width
    var h = 400; // height
    var x = d3.scale.linear().domain([0, 20]).range([0, w]); // 24 for days
    var y = d3.scale.linear().domain([0, 58]).range([h,0]);
    var xAxis = d3.svg.axis().scale(x).orient("bottom"); //x axis at bottom
    var yAxis = d3.svg.axis().scale(y).orient("left"); // y axis on left
    var line = d3.svg.line()
    .x(function(d, i) {return x(d.date);})
    .y(function(d, i) {return y(d.close);});
    var graph = d3.select("#graph").append("svg:svg").attr("width", w )
            .attr("height", h+ 200 ).append("svg:g")
            .attr("transform", "translate(" + 100 + "," + 100 + ")"); // move chart down 
 and right
            graph.append("g").attr("class", "x axis")
             .attr("transform", "translate(0," + h + ")").call(xAxis);
    graph.append("g").attr("class", "y axis").call(yAxis);
            graph.append("text").attr("class", "x label")
            .attr("text-anchor", "end").attr("x", w - (w / 2))
            .attr("y", h + 45).text("Time in Days");
            graph.append("text").attr("class", "y label")
            .attr("text-anchor", "end").attr("y", -60).attr("x", -60)
            .attr("dy", ".75em").attr("transform", "rotate(-90)")
            .text("Number of Visits");
    graph.append("svg:path").attr("d", line(data)); // red line
 }
</script>
</html>

我在另一个文件中的数据集被命名为"data.json",它包含:

[                                    
{date:"00",close:"55"},         
{date:"07",close:"10"},
{date:"10",close:"58"},
{date:"15",close:"46"},
{date:"20",close:"05"}
]

最好使用交叉过滤器,而不是用D3编写代码。