使用csv发出d3折线图

时间:2013-11-15 11:43:14

标签: javascript csv d3.js

我是这个d3的新手(并且是一般的公平编程)。由于这个原因,我一直试图将其他人的例子转变为我所追求的(希望这是一个相当简单的折线图)。我一直在看这个例子:

http://bl.ocks.org/nsonnad/4175202

我希望能够切换我正在绘制的系列(以及我正在绘制的变量,但我希望我的.csv中的空值将限制此变量)的功能以及该行的突出显示当鼠标翻过来时。因此,我试图取出引用组的位并更改下拉菜单以匹配csv,希望这样可行 - 但事实并非如此。

我的html和csv文件在下面,你可爱的人可以给我的任何帮助或指示都是最热情的

我是否还可以检查我的假设,即列中的空金额将意味着该变量不会被列为不相关的故障。

提前谢谢大家

的index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Starts</title>
    <script type="text/javascript" src="http://d3js.org/d3.v2.min.js"></script>
<style type="text/css">

body {
  font: 12px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.x.axis path {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.line {
  fill: none;
  stroke-width: 7px;
}

.country {opacity: 0.3;}
.country:hover {opacity:1;}

</style>
</head>
<body>
  <p id="menu"><b>Starts</b><br>Select series: <select>
    <option value="TOT">Total</option>
    <option value="AREA">Area</option>
    <option value="AGE">Age</option>
    <option value="SEX">Gender</option></select>

  <script type="text/javascript">

    var margin = {top: 20, right: 80, bottom: 30, left: 50},
        w = 660 - margin.left - margin.right,
        h = 400 - margin.top - margin.bottom,
        x = d3.time.scale().range([0, w]),
        y = d3.scale.linear().range([h, 0]);
        parseDate = d3.time.format("%b-&y").parse;

    var color = d3.scale.category10();

 var countries,
transpose;


    var line = d3.svg.line()
       .interpolate("basis")
       .x(function(d) { return x(d.month); })
       .y(function(d) { return y(d.stat); });


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


    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
       svg.append("svg:g")
        .attr("class", "x axis");


    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        svg.append("svg:g")
        .attr("class", "y axis");


    var menu = d3.select("#menu select")
    .on("change", change);   


d3.csv("data.csv", function(csv) {
        countries = csv;
        redraw();
    });

d3.select(window)
    .on("keydown", function() { altKey = d3.event.altKey; })
    .on("keyup", function() { altKey = false; });

var altKey;


function change() {
  clearTimeout(timeout);

  d3.transition()
      .duration(altKey ? 7500 : 1500)
      .each(redraw);
}


function redraw() {


    var nested = d3.nest()
        .key(function(d) { return d.indicatorCode; })
        .map(countries)

    var series = menu.property("value");


    var data = nested[series];

    var keyring = d3.keys(data[0]).filter(function(key) {
             return (key !== "indicatorName" && key !== "monthCode" && key !== "indicatorCode" && key !== "month");
         });

     var transpose = keyring.map(function(name) {
            return {
              name: name,
              values: data.map(function(d) {
                return {month: parseDate(d.month), stat: +d[name]};
              })
            };
        });


    x.domain([
    d3.min(transpose, function(c) { return d3.min(c.values, function(v) { return v.month; }); }),
    d3.max(transpose, function(c) { return d3.max(c.values, function(v) { return v.month; }); })
  ]);

    y.domain([
    d3.min(transpose, function(c) { return d3.min(c.values, function(v) { return v.stat; }); }),
    d3.max(transpose, function(c) { return d3.max(c.values, function(v) { return v.stat; }); })
  ]);

    var country = svg.selectAll(".country")
      .data(transpose);


    var countryEnter = country.enter().append("g")
      .attr("class", "country")
      .attr("id", function(d) { return d.name; });


    countryEnter.append("path")
      .attr("class", "line")
      .attr("d", function(d) { return line(d.values); })
      .style("stroke", function(d) { return color(d.name); });


    countryEnter.append("text")
     .attr("class", "names")
     .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
     .attr("transform", function(d) { return "translate(" + x(d.value.month) + "," + y(d.value.stat) + ")"; })
     .attr("x", 4)
     .attr("dy", ".35em")
     .text(function(d) { return d.name; });


    var countryUpdate = d3.transition(country);

    countryUpdate.select("path")
      .attr("d", function(d) { return line(d.values); });

    countryUpdate.select("text")
       .attr("transform", function(d) { return "translate(" + x(d.values[d.values.length - 1].month) + "," + y(d.values[d.values.length - 1].stat) + ")"; });


      d3.transition(svg).select(".y.axis")
          .call(yAxis);  

      d3.transition(svg).select(".x.axis")
            .attr("transform", "translate(0," + h + ")")
          .call(xAxis);

}

var timeout = setTimeout(function() {
  menu.property("value", "SEX").node().focus();
  change();
}, 7000);


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

data.csv

indicatorName,indicatorCode,month,monthCode,Total,Area1,Area2,Area2,Area4,Youngster,Middle aged,Elderly,Male,Female
Total,TOT,2011/05,MthMay11,22,,,,,,,,,
Total,TOT,2011/06,MthJun11,49,,,,,,,,,
Total,TOT,2011/07,MthJul11,489,,,,,,,,,
Total,TOT,2011/08,MthAug11,1002,,,,,,,,,
Total,TOT,2011/09,MthSep11,3097,,,,,,,,,
Area,AREA,2011/05,MthMay11,,22,,,,,,,,
Area,AREA,2011/06,MthJun11,,24,11,7,7,,,,,
Area,AREA,2011/07,MthJul11,,167,248,68,6,,,,,
Area,AREA,2011/08,MthAug11,,500,390,210,260,,,,,
Area,AREA,2011/09,MthSep11,,590,580,390,540,,,,,
Age,AGE,2011/05,MthMay11,,,,,,19,3,,,
Age,AGE,2011/06,MthJun11,,,,,,21,12,16,,
Age,AGE,2011/07,MthJul11,,,,,,110,89,290,,
Age,AGE,2011/08,MthAug11,,,,,,143,144,715,,
Age,AGE,2011/09,MthSep11,,,,,,472,615,2010,,
Gender,SEX,2011/05,MthMay11,,,,,,,,,11,11
Gender,SEX,2011/06,MthJun11,,,,,,,,,24,25
Gender,SEX,2011/07,MthJul11,,,,,,,,,244,245
Gender,SEX,2011/08,MthAug11,,,,,,,,,508,494
Gender,SEX,2011/09,MthSep11,,,,,,,,,1787,1310

simpleline.html

<!DOCTYPE html>
<meta charset="utf-8">

<link href="nv.d3.css" rel="stylesheet" type="text/css">

<style>

body {
  overflow-y:scroll;
}

text {
  font: 12px sans-serif;
}

svg {
  display: block;
}

#chart1 svg {
  height: 500px;
  min-width: 200px;
  min-height: 100px;
/*
  margin: 50px;
  Minimum height and width is a good idea to prevent negative SVG dimensions...
  For example width should be =< margin.left + margin.right + 1,
  of course 1 pixel for the entire chart would not be very useful, BUT should not have errors
*/

}
#chart1 {
  margin-top: 200px;
  margin-left: 100px;
}
</style>
<body class='with-3d-shadow with-transitions'>

<div id="chart1" >
  <svg style="height: 500px;"></svg>
</div>

<script src="d3.v3.js"></script>
<script src="nv.d3.js"></script>
<script src="tooltip.js"></script>
<script src="utils.js"></script>
<script src="interactiveLayer.js"></script>
<script src="legend.js"></script>
<script src="axis.js"></script>
<script src="scatter.js"></script>
<script src="line.js"></script>
<script src="lineChart.js"></script>

<script>
// Wrapping in nv.addGraph allows for '0 timeout render', stores rendered charts in nv.graphs, and may do more in the future... it's NOT required
var chart;

nv.addGraph(function() {
  chart = nv.models.lineChart()
  .options({
    margin: {left: 100, bottom: 100},
    showXAxis: true,
    showYAxis: true,
    transitionDuration: 250
  })
  ;

  // chart sub-models (ie. xAxis, yAxis, etc) when accessed directly, return themselves, not the parent chart, so need to chain separately
  chart.xAxis
    .axisLabel("Month")
    .tickFormat(d3.time.format('%b'));

  chart.yAxis
    .axisLabel('Number')
    .tickFormat(d3.format(',.0f'))
    ;

  d3.select('#chart1 svg')
    .datum(sinAndCos())
    .call(chart);

  //TODO: Figure out a good way to do this automatically
  nv.utils.windowResize(chart.update);
  //nv.utils.windowResize(function() { d3.select('#chart1 svg').call(chart) });

  chart.dispatch.on('stateChange', function(e) { nv.log('New State:', JSON.stringify(e)); });

  return chart;
});

function sinAndCos() {
var tot= [{x:new Date("May 31, 2013"), y:200}, {x:new Date("June 30, 2013"), y:500}, {x:new Date("July 31, 2013"), y:1600}, {x:new Date("August 31, 2013"), y:2700}, {x:new Date("September 31, 2013"), y:3800}],
    Age1= [{x:new Date("May 31, 2013"), y:200}, {x:new Date("June 30, 2013"), y:350}, {x:new Date("July 31, 2013"), y:1200}, {x:new Date("August 31, 2013"), y:2200}, {x:new Date("September 31, 2013"), y:2900}],
    Age2= [{x:new Date("May 31, 2013"), y:0}, {x:new Date("June 30, 2013"), y:100}, {x:new Date("July 31, 2013"), y:300}, {x:new Date("August 31, 2013"), y:400}, {x:new Date("September 31, 2013"), y:600}],
    Age3= [{x:new Date("May 31, 2013"), y:0}, {x:new Date("June 30, 2013"), y:50}, {x:new Date("July 31, 2013"), y:100}, {x:new Date("August 31, 2013"), y:100}, {x:new Date("September 31, 2013"), y:300}]
        ;

      return [
        {
          values: tot,
          key: "Total",
          color: "#ff7f0e"
        },
        {
          values: Age1,
          key: "Youngster",
          color: "#2ca02c"
        },
        {
          values: Age2,
          key: "Middle Aged",
          color: "#2222ff"
        }
        ,
        {
          values: Age3,
          key: "Old Person",
          color: "#667711"
        }
      ];
    }

    </script>

0 个答案:

没有答案