Treeno1
Treeno1

Reputation: 139

How to pull information from a CSV file for use in a stacked bar chart

I have a real data set (https://data.gov.uk/dataset/road-traffic-accidents - 2009) which im trying to pull information from, it has roughly 2500 items, as a sample -

enter image description here

I'm using d3 to create a stacked bar chart which displays the categories on the x axis - "slight, serious, fatal" and the frequency of the accidents for each category on the y axis. the actual bars themselves will be split into how many of these accidents were female and male.

currently though, I'm trying to figure out how to best pull the information from the csv. Having had a look at a few examples of various d3 stacked charts, the data seems to be arranged like such (example from - http://www.adeveloperdiary.com/d3-js/create-stacked-bar-chart-using-d3-js/) -

	var data=[
 
    {month:'Jan', A:20, B: 5,  C: 10},
    {month:'Feb', A:25, B: 10, C: 20}

    ]
var xData = ["A", "B", "C"];

so using that example as a basis, i'm guessing maybe the best way format the data from this particular csv would be ? -

	var data = [

		{'Casualty Severity':'Slight', 'Male': 1567, 'Female': 1200 },
		{'Casualty Severity':'Serious', 'Male': 100, 'Female': 120 },
		{'Casualty Severity':'Fatal', 'Male': 15, 'Female': 5 }
	]

unfortunately I am not very good at formatting the data, but roughly know how to pull using d3.nest

	d3.csv('/road_accidents/2009.csv', function(data) {
		var severity = d3.nest()
			.key(function(d) {
				return d['Casualty Severity'];
			})
			.entries(data);
			
		console.log(severity)
	})

which provides this out put in the console -

enter image description here

extended looking like this -

enter image description here

So i suppose, the question is what is the best way to format the data, using a real data set for use in a stacked bar chart, and would this be the correct way of doing it?

any help would be hugely appreciated!

Upvotes: 0

Views: 359

Answers (1)

sparta93
sparta93

Reputation: 3854

This is one way to organize your data which would make it easy to use when building your stacked bar chart. It could be simplified further if you don't want it to be nested so much.

var url = "https://aql.datapress.com/leeds/dataset/road-traffic-accidents/2016-05-19T15:29:13/2009.csv";

d3.csv(url, function(data) {
  var severityBySex = d3.nest()
    .key(function(d) { return d['Casualty Severity'];})
    .key(function(d) { return d['Sex of Casualty']; })
    .entries(data);
    
    for (var i = 0; i < severityBySex.length; i++){
       console.log(severityBySex[i].key + " - " + "MALE: "  + 	
       severityBySex[i].values[0].values.length + " - " 
       + "FEMALE: " + severityBySex[i].values[1].values.length);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Upvotes: 1

Related Questions