如何在代码中使用本地目录csv文件而不是硬编码?

时间:2014-07-16 14:45:08

标签: html csv d3.js visualization bar-chart

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Generated with d3-generator.com -->
<html>
  <head>
     <title>Bar Chart</title>
     <meta http-equiv="X-UA-Compatible" content="IE=9">
  </head>    
  <body>
    <div id="chart"></div>
    <script src="http://d3js.org/d3.v2.min.js"></script>
    <script>

function renderChart() {

/*var data = d3.csv.("Cancer_No_Of_Deaths_per_100000.csv", function(d) {
});*/
var data = d3.csv.parse(d3.select('#csv').text());

上面一行是使用下面csv文件的硬编码脚本。 我想将代码更改为var data = d3.csv。(“myFile.csv”),但是当我更改它时没有任何内容出现。所以我想寻求帮助,看看能够从本地目录更改csv文件的读取的正确方法是什么,而不是像上面的代码那样在脚本中硬编码csv。

var valueLabelWidth = 40; // space reserved for value labels (right)
var barHeight = 20; // height of one bar
var barLabelWidth = 100; // space reserved for bar labels
var barLabelPadding = 5; // padding between bar and bar labels (left)
var gridLabelHeight = 18; // space reserved for gridline labels
var gridChartOffset = 3; // space between start of grid and first bar
var maxBarWidth = 420; // width of the bar with the max value

// accessor functions 
var barLabel = function(d) { return d['country'] + " " + d['gender']; };
var barValue = function(d) { return parseFloat(d['deaths']); };


// scales
var yScale = d3.scale.ordinal().domain(d3.range(0, data.length)).rangeBands([0, data.length * barHeight]);
var y = function(d, i) { return yScale(i); };
var yText = function(d, i) { return y(d, i) + yScale.rangeBand() / 2; };
var x = d3.scale.linear().domain([0, d3.max(data, barValue)]).range([0, maxBarWidth]);
// svg container element
var chart = d3.select('#chart').append("svg")
  .attr('width', maxBarWidth + barLabelWidth + valueLabelWidth)
  .attr('height', gridLabelHeight + gridChartOffset + data.length * barHeight);
// grid line labels
var gridContainer = chart.append('g')
  .attr('transform', 'translate(' + barLabelWidth + ',' + gridLabelHeight + ')'); 
gridContainer.selectAll("text").data(x.ticks(10)).enter().append("text")
  .attr("x", x)
  .attr("dy", -3)
  .attr("text-anchor", "middle")
  .text(String);
// vertical grid lines
gridContainer.selectAll("line").data(x.ticks(10)).enter().append("line")
  .attr("x1", x)
  .attr("x2", x)
  .attr("y1", 0)
  .attr("y2", yScale.rangeExtent()[1] + gridChartOffset)
  .style("stroke", "#ccc");
// bar labels
var labelsContainer = chart.append('g')
  .attr('transform', 'translate(' + (barLabelWidth - barLabelPadding) + ',' + (gridLabelHeight + gridChartOffset) + ')'); 
labelsContainer.selectAll('text').data(data).enter().append('text')
  .attr('y', yText)
  .attr('stroke', 'none')
  .attr('fill', 'black')
  .attr("dy", ".35em") // vertical-align: middle
  .attr('text-anchor', 'end')
  .text(barLabel);
// bars
var barsContainer = chart.append('g')
  .attr('transform', 'translate(' + barLabelWidth + ',' + (gridLabelHeight + gridChartOffset) + ')'); 
barsContainer.selectAll("rect").data(data).enter().append("rect")
  .attr('y', y)
  .attr('height', yScale.rangeBand())
  .attr('width', function(d) { return x(barValue(d)); })
  .attr('stroke', 'white')
  .attr('fill', 'steelblue');
// bar value labels
barsContainer.selectAll("text").data(data).enter().append("text")
  .attr("x", function(d) { return x(barValue(d)); })
  .attr("y", yText)
  .attr("dx", 3) // padding-left
  .attr("dy", ".35em") // vertical-align: middle
  .attr("text-anchor", "start") // text-align: right
  .attr("fill", "black")
  .attr("stroke", "none")
  .text(function(d) { return d3.round(barValue(d), 2); });
// start line
barsContainer.append("line")
  .attr("y1", -gridChartOffset)
  .attr("y2", yScale.rangeExtent()[1] + gridChartOffset)
  .style("stroke", "#000");

}
    </script>
    <script id="csv" type="text/csv">country,year,gender,deaths
Afghanistan,2008,Female,97
Afghanistan,2008,Male,108

</script>
    <script>renderChart();</script>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

d3.csv以异步方式执行,因此您需要将回调函数传递给它。例如,您可以将data作为renderChart的参数,然后调用d3.csv("myFile.csv", renderChart)。进行此更改会在我的计算机上生成以下图表:

enter image description here

这是更新的Javascript:

var data = d3.csv("myFile.csv", renderChart);

function renderChart(data) {

    var valueLabelWidth = 40; // space reserved for value labels (right)
    var barHeight = 20; // height of one bar
    var barLabelWidth = 100; // space reserved for bar labels
    var barLabelPadding = 5; // padding between bar and bar labels (left)
    var gridLabelHeight = 18; // space reserved for gridline labels
    var gridChartOffset = 3; // space between start of grid and first bar
    var maxBarWidth = 420; // width of the bar with the max value

    // accessor functions 
    var barLabel = function (d) {
        return d['country'] + " " + d['gender'];
    };
    var barValue = function (d) {
        return parseFloat(d['deaths']);
    };


    // scales
    var yScale = d3.scale.ordinal().domain(d3.range(0, data.length)).rangeBands([0, data.length * barHeight]);
    var y = function (d, i) {
        return yScale(i);
    };
    var yText = function (d, i) {
        return y(d, i) + yScale.rangeBand() / 2;
    };
    var x = d3.scale.linear().domain([0, d3.max(data, barValue)]).range([0, maxBarWidth]);
    // svg container element
    var chart = d3.select('#chart').append("svg")
        .attr('width', maxBarWidth + barLabelWidth + valueLabelWidth)
        .attr('height', gridLabelHeight + gridChartOffset + data.length * barHeight);
    // grid line labels
    var gridContainer = chart.append('g')
        .attr('transform', 'translate(' + barLabelWidth + ',' + gridLabelHeight + ')');
    gridContainer.selectAll("text").data(x.ticks(10)).enter().append("text")
        .attr("x", x)
        .attr("dy", -3)
        .attr("text-anchor", "middle")
        .text(String);
    // vertical grid lines
    gridContainer.selectAll("line").data(x.ticks(10)).enter().append("line")
        .attr("x1", x)
        .attr("x2", x)
        .attr("y1", 0)
        .attr("y2", yScale.rangeExtent()[1] + gridChartOffset)
        .style("stroke", "#ccc");
    // bar labels
    var labelsContainer = chart.append('g')
        .attr('transform', 'translate(' + (barLabelWidth - barLabelPadding) + ',' + (gridLabelHeight + gridChartOffset) + ')');
    labelsContainer.selectAll('text').data(data).enter().append('text')
        .attr('y', yText)
        .attr('stroke', 'none')
        .attr('fill', 'black')
        .attr("dy", ".35em") // vertical-align: middle
    .attr('text-anchor', 'end')
        .text(barLabel);
    // bars
    var barsContainer = chart.append('g')
        .attr('transform', 'translate(' + barLabelWidth + ',' + (gridLabelHeight + gridChartOffset) + ')');
    barsContainer.selectAll("rect").data(data).enter().append("rect")
        .attr('y', y)
        .attr('height', yScale.rangeBand())
        .attr('width', function (d) {
        return x(barValue(d));
    })
        .attr('stroke', 'white')
        .attr('fill', 'steelblue');
    // bar value labels
    barsContainer.selectAll("text").data(data).enter().append("text")
        .attr("x", function (d) {
        return x(barValue(d));
    })
        .attr("y", yText)
        .attr("dx", 3) // padding-left
    .attr("dy", ".35em") // vertical-align: middle
    .attr("text-anchor", "start") // text-align: right
    .attr("fill", "black")
        .attr("stroke", "none")
        .text(function (d) {
        return d3.round(barValue(d), 2);
    });
    // start line
    barsContainer.append("line")
        .attr("y1", -gridChartOffset)
        .attr("y2", yScale.rangeExtent()[1] + gridChartOffset)
        .style("stroke", "#000");

}