My data is as follows:
var chartData = [[9.402974983096687, "Asian"], [10.762177012177013, "Black"], [12.213470319634704, "Chinese"], [11.211221431247658, "Hispanic"], [9.18421052631579, "American Indian"], [12.36144578313253, "Japanese"], [14.659334126040427, "Other"], [7.5, "Portuguese"], [10.636304446904095, "White"]];
I am trying to convert it to a format:
[
{
"Ethinicity": "Asian",
"Facebook_usage": 9.40
},
{
"Ethinicity" : "Black",
"Freq": 12.213470319634704
},
{
"Ethinicity":"Chinese"
"Freq": 12.213470319634704
},
----]
Then, make a bar chart from this. Tried using a map function as follows:
chartData.map(function(e, i) {
facebook_usage.push(e[0]);
ethinicity.push(e[1]);
}
var chartData = create_JSON(facebook_usage,ethinicity) {
--not sure how to frame this function }
Here is the rest of the code to plot the bar chart:
var margin = {top: 20, right: 20, bottom: 70, left: 40},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// set the ranges
var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);
var y = d3.scale.linear().range([height, 0]);
// define the axis
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);
// add the SVG element
var svg = d3.select("body").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 + ")");
// load the data
chartData.forEach(function(d) {
d.ethinicity = d.ethinicity;
d.facebook_usage = d.facebook_usage;
});
// scale the range of the data
x.domain(data.map(function(d) { return d.ethinicity; }));
y.domain([0, d3.max(data, function(d) { return d.facebook_usage; })]);
// add axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", "-.55em")
.attr("transform", "rotate(-90)" );
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 5)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Frequency");
// Add bar chart
svg.selectAll("bar")
.data(chartData)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.ethinicity); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.facebook_usage); })
.attr("height", function(d) { return height - y(d.facebook_usage); });
Still trying to find my way around d3.js. Below is the fiddle