Histogram with values from csv

2019-07-31 23:56发布

问题:

I am trying to create a simple histogram with values stored in a csv (that I will be modifying through the time).

The code I am using now is: (edited code!)

               var values = []

                d3.csv('../static/CSV/Chart_data/histogram_sub.csv?rnd='+(new Date).getTime(),function(data){

                    values = Object.keys(data).map(function(k){ return data[k]['Calculus I']});

                    var color = "steelblue";

                    // Generate a 1000 data points using normal distribution with mean=20, deviation=5

                    // A formatter for counts.
                    var formatCount = d3.format(",.0f");

                    var margin = {top: 20, right: 30, bottom: 30, left: 30},
                        width = 800 - margin.left - margin.right,
                        height = 400 - margin.top - margin.bottom;

                    var max = d3.max(values);
                    var min = d3.min(values);
                    var x = d3.scale.linear()
                          .domain([min, max])
                          .range([0, width]);

                    // Generate a histogram using twenty uniformly-spaced bins.
                    var data = d3.layout.histogram()
                        .bins(x.ticks(20))
                        (values);

                    var yMax = d3.max(data, function(d){return d.length});
                    var yMin = d3.min(data, function(d){return d.length});
                    var colorScale = d3.scale.linear()
                                .domain([yMin, yMax])
                                .range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);

                    var y = d3.scale.linear()
                        .domain([0, yMax])
                        .range([height, 0]);

                    var xAxis = d3.svg.axis()
                        .scale(x)
                        .orient("bottom");

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

                    var bar = svg.selectAll(".bar")
                        .data(data)
                      .enter().append("g")
                        .attr("class", "bar")
                        .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

                    bar.append("rect")
                        .attr("x", 1)
                        .attr("width", (x(data[0].dx) - x(0)) - 1)
                        .attr("height", function(d) { return height - y(d.y); })
                        .attr("fill", function(d) { return colorScale(d.y) });

                    bar.append("text")
                        .attr("dy", ".75em")
                        .attr("y", -12)
                        .attr("x", (x(data[0].dx) - x(0)) / 2)
                        .attr("text-anchor", "middle")
                        .text(function(d) { return formatCount(d.y); });

                    svg.append("g")
                        .attr("class", "x axis")
                        .attr("transform", "translate(0," + height + ")")
                        .call(xAxis);
                });

And my csv file looks like this:

Calculus I
5.0
5.1
5.7
...

And I am getting errors that I think refer to data[0]:

Uncaught TypeError: Cannot read property 'dx' of undefined

Any help? Thanks in advance!

回答1:

Here's a plunkr using d3.csv and fetching data from the file:

http://plnkr.co/edit/2xCvrwiXWzrS6gtbmIU7?p=preview

And please go through the docs for d3.csv

Using the same, here are the relevant changes to the code:

  1. Added a new file test.csv with the content.
  2. Fetched the file using d3.csv:

    d3.csv("test.csv", parse, function(error, data) { 
       console.log(data);
    });
    
  3. The parse that you see above is a accessor function that receives every row from the csv and I'm using it to parse the integer value.

    function parse(row) {
      row['Calculus I'] = +row['Calculus I'];
      return row;
    }
    
  4. And as you were assuming values to be array of integers, I'm mapping the fetched data in the same format as desired using map

    values = data.map(function(d) { return d['Calculus I']; });
    

Hope this helps.



回答2:

What you need to do is first read the csv using d3.csv and then convert it to an array of values

var values = []

d3.csv("**csv file path**",function(data){
    //This will internally convert csv to a json and then we can extract all values and transform it into an array
    values = Object.keys(data).map(function(k){ return data[k]['Calculus I']});

    //If the above code is too complex for you
    //for(i in data){
    //   values.push(data[i]['Calculus I']
    //}
});

//Rest of the chart rendering code goes here