estebanpdl
estebanpdl

Reputation: 1233

Count text fields from csv dataset in d3 js

I'm working with d3.js in order to make a simple bar chart. I have made bar charts using d3.csv data. However, now I'm trying to use only one column from csvfile.

All items from this column are string values, specifically, they're cities. Some of them are unique, but others appears more than once.

Example:

city
Mor
Gdl
Mex
Bog
Mad
Rio
Bar
Mor
Gdl
Mor
Rio
Mor
Bog
Mor

I want to create a bar chart using this column. x value will be the City and y value will be the number of times the city appears.

I'm working with this code. However, I can not get y value:

d3.csv("../cities.csv", function(error, dataset) {
    dataset.forEach( function(d) {
        d.count = +d.city;
    });
    x.domain(dataset.map( function(d) { return d.city; }));
    y.domain([0, d3.max(dataset, function(d) { return d.count; })]);
    svg.append('g')
        .attr('class', 'x axis')
        .attr('transform', 'translate(0,' + h + ")")
        .call(xAxis);
    svg.append('g')
        .attr('class', 'y axis')
        .call(yAxis)
        .append('text')
        .attr('transform', 'rotate(-90)')
        .attr('y', 6)
        .attr('dy', '.71em')
        .style('text-anchor', 'end')
        .text('Número de contratistas');
    var bars = svg.selectAll('.bar')
        .data(dataset)
        .enter()
        .append('rect')
        .attr('class', 'bar')
        .attr('x', function(d) { return x(d.city); })
        .attr('width', x.rangeBand())
        .attr('y', function(d) { return y(d.count); })
        .attr('height', function(d) { return h - y(dataset.map(d.count));});
});

From this code, my first attempt to get the counting from each city was:

dataset.forEach( function(d) {
    d.count = +d.city;
});

How can I improve this fucntion in order to get this kind of bar chart?

Any suggestions to improve it are welcome! Thanks.

Upvotes: 1

Views: 2337

Answers (1)

Stuurpiek
Stuurpiek

Reputation: 68

If I understand you right you would like to count how often each city occurs and store it in d.count. Try this:

// define count object that holds count for each city
var countObj = {};

// count how much each city occurs in list and store in countObj
dataset.forEach(function(d) {
    var city = d.value;
    if(countObj[city] === undefined) {
        countObj[city] = 0;
    } else {
        countObj[city] = countObj[city] + 1;
    }
});
// now store the count in each data member
dataset.forEach(function(d) {
    var city = d.value;
    d.count = countObj[city];
});

Upvotes: 1

Related Questions