D3 Stacked bar graph works in Tributary but nowhere else - javascript

This has the expected results I want but when I import the code into my HTML file as a script it doesn't show anything at all.
var PUBLIC = [50,40,10];
var NONPROFIT = [30,40,30];
var FOR_PROFIT = [70,15,15];
var data = [
{"key":"PUBLIC", "pop1":PUBLIC[0], "pop2":PUBLIC[1], "pop3":PUBLIC[2]},
{"key":"NONPROFIT", "pop1":NONPROFIT[0], "pop2":NONPROFIT[1], "pop3":NONPROFIT[2]},
{"key":"FORPROFIT", "pop1":FOR_PROFIT[0], "pop2":FOR_PROFIT[1], "pop3":FOR_PROFIT[2]}
];
var n = 3, // Number of layers
m = data.length, // Number of samples per layer
stack = d3.layout.stack(),
labels = data.map(function(d) { return d.key; }),
// Go through each layer (pop1, pop2 etc, that's the range(n) part)
// then go through each object in data and pull out that objects's population data
// and put it into an array where x is the index and y is the number
layers = stack(d3.range(n).map(function(d)
{
var a = [];
for (var i = 0; i < m; ++i)
{
a[i] = { x: i, y: data[i]['pop' + (d+1)] };
}
return a;
})),
// The largest single layer
yGroupMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y; }); }),
// The largest stack
yStackMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); });
var margin = {top: 40, right: 10, bottom: 20, left: 50},
width = 677 - margin.left - margin.right,
height = 533 - margin.top - margin.bottom;
var y = d3.scale.ordinal()
.domain(d3.range(m))
.rangeRoundBands([2, height], .08);
var x = d3.scale.linear()
.domain([0, yStackMax])
.range([0, width]);
var color = d3.scale.linear()
.domain([0, n - 1])
.range(["#aad", "#556"]);
var svg = d3.select("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 layer = svg.selectAll(".layer")
.data(layers)
.enter().append("g")
.attr("class", "layer")
.style("fill", function(d, i) { return color(i); });
layer.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("y", function(d) { return y(d.x); })
.attr("x", function(d) { return x(d.y0); })
.attr("height", y.rangeBand())
.attr("width", function(d) { return x(d.y); });
var yAxis = d3.svg.axis()
.scale(y)
.tickSize(1)
.tickPadding(6)
.tickValues(labels)
.orient("left");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
I believe I have all the required libraries imported and then some:
<!-- D3 Library -->
<script src='https://d3js.org/d3.v3.min.js' charset='utf-8'></script>
<!-- jQuery Mobile -->
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!-- jQuery Main -->
<script src='https://code.jquery.com/jquery-2.2.3.min.js' charset='utf-8'></script>
While the code to get my variables are a bit simplified (i.e. plainly setting my arrays) they are the same format as what is put within the data array.
Furthermore, this example does not work within CodePen either when I import everything that Tributary uses for its base libraries. While, again, this isn't 100% of the code I have going into the creation a much simpler working example on Tributary does not work on CodePen.
D3 has done nothing but kick my butt these past few weeks and I'm in need of some guidance. Thanks.

You need to wait for the page to be fully loaded or your can put the code before the closing </body> tag.
Solution1:
$(function() {
//Put your code here;
});
Solution2:
<body>
<svg></svg>
<script>
//your code here
</script>
</body>
Demo: https://jsfiddle.net/iRbouh/ag6p4kkg/

Related

How to get the index of the data element in a histogram on mouseover?

I have a d3.v3.min.js histogram created using this as reference Histogram chart using d3 and I'd like to highlight in a separate plot (scatter plot) all the points that fall within one bar of this histogram. To this end I hook on the mouseover event of the rectangle to get the values within one bin. This works fine but I can't get their indices from the original input array:
var data = d3.layout.histogram().bins(xTicks)(values);
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) })
.on("mouseover", function (d, i) { console.log(d); });
d is an array containing all the values within the bin, and i is the bin index. I need the indices of the original data values I passed to the histogram function so that I can look them up in the other plot by index (as opposed to a binary search needed on the value).
Instead of just passing number values to the histogram generator you could create an array of objects carrying additional information:
// Generate a 1000 data points using normal distribution with mean=20, deviation=5
var f = d3.random.normal(20, 5);
// Create full-fledged objects instead of mere numbers.
var values = d3.range(1000).map(id => ({
id: id,
value: f()
}));
// Accessor function for the objects' value property.
var valFn = d => d.value;
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(20))
.value(valFn) // Provide accessor function for histogram generation
(values);
By providing an accessor function to the histogram generator you are then able to create the bins from this array of objects. Calling the histogram generator will consequently result in bins filled with objects instead of just raw numbers. In an event handler you are then able to access your data objects by reference. The objects will carry all the initial information, be it the id property as in my example, an index or anything else you put in them in the first place.
Have a look at the following snippet for a working demo:
var color = "steelblue";
var f = d3.random.normal(20, 5);
// Generate a 1000 data points using normal distribution with mean=20, deviation=5
var values = d3.range(1000).map(id => ({
id: id,
value: f()
}));
var valFn = d => d.value;
// A formatter for counts.
var formatCount = d3.format(",.0f");
var margin = {top: 20, right: 30, bottom: 30, left: 30},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var max = d3.max(values, valFn);
var min = d3.min(values, valFn);
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))
.value(valFn)
(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("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 + ")");
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) + ")"; })
.on("mouseover", d => { console.log(d)});
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);
/*
* Adding refresh method to reload new data
*/
function refresh(values){
// var values = d3.range(1000).map(d3.random.normal(20, 5));
var data = d3.layout.histogram()
.value(valFn)
.bins(x.ticks(20))
(values);
// Reset y domain using new data
var yMax = d3.max(data, function(d){return d.length});
var yMin = d3.min(data, function(d){return d.length});
y.domain([0, yMax]);
var colorScale = d3.scale.linear()
.domain([yMin, yMax])
.range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);
var bar = svg.selectAll(".bar").data(data);
// Remove object with data
bar.exit().remove();
bar.transition()
.duration(1000)
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
bar.select("rect")
.transition()
.duration(1000)
.attr("height", function(d) { return height - y(d.y); })
.attr("fill", function(d) { return colorScale(d.y) });
bar.select("text")
.transition()
.duration(1000)
.text(function(d) { return formatCount(d.y); });
}
// Calling refresh repeatedly.
setInterval(function() {
var values = d3.range(1000).map(id => ({
id: id,
value: f()
}));
refresh(values);
}, 2000);
body {
font: 10px sans-serif;
}
.bar rect {
shape-rendering: crispEdges;
}
.bar text {
fill: #999999;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.as-console-wrapper {
height: 20%;
}
<script src="https://d3js.org/d3.v3.min.js"></script>

d3.csv linked GitHub

I'm trying to link my .csv stored in github to the my d3 code.
Does anybody know if there is anything that I'm missing? I was able to do it with LeafLet not with D3. Any help would be highly appreciated. Thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3!!</title>
</head>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.js">
</script>
<script src="https://d3js.org/d3-selection-multi.v0.4.min.js"></script>
<script>
var outerWidth=500;
var outerheight=250;
var margin={left:-50, top:0, right:-50, bottom:0};
var xColumn="longitude";
var yColumn="latitude";
var rColumn="population";
var peoplePerPixel=1000000;
var innerWidth=outerWidth - margin.left - margin.right;
var innerHeight=outerheight - margin.top - margin.bottom;
var svg=d3.select("body").append("svg")
.attr("width", outerWidth)
.attr("height", outerheight);
var g= svg.append("g")
.attr("transform", "translate (" + margin.left + "," +margin.top +")");
var xScale= d3.scaleLog()
.range([0,innerWidth]);
var yScale= d3.scaleLog()
.range([innerHeight,0]);
var rScale= d3.scaleSqrt();
function render (data){
xScale.domain(d3.extent(data, function (d){return d[xColumn]; }));
yScale.domain(d3.extent(data, function (d){return d[yColumn]; }));
rScale.domain([0, d3.max(data, function (d){return d[xColumn]; })]);
var circles= svg.selectAll("circle").data(data);
circles.enter().append("circle");
circles
.attr("cx", function(d){ return xScale(d[xColumn]);})
.attr("cy", function(d){ return yScale(d[yColumn]);})
.attr("r", function(d){ return rScale(d[rColumn]);});
circles.exit().remove();
}
function type(d) {
d.latitude=+d.latitude;
d.longitude=+d.longitude;
d.population=+d.population;
return d;
}
var data =
d3.csv(
"https://raw.githubusercontent.com/Pre60/myTest/master/map_cities.csv",
type, render)
</script>
</body>
</html>
You have some problems here:
You're setting the attributes to an "update" selection. This will not work (unless you call the function twice). It has to be:
circles.enter()
.append("circle")
.attr("cx", function(d) {
//etc...
because of that, there were no circles in your SVG. However, changing that point #1 shows you two additional problems:
You're using a scaleLog with a domain that crosses zero. There is no log of zero (actually, it is minus infinity). As the API clearly says:
As log(0) = -∞, a log scale domain must be strictly-positive or strictly-negative; the domain must not include or cross zero.
So, use a linear scale instead.
You are using the wrong property for the radii. It should be rColumn.
You forgot to set the range of the rScale.
All together, this is your (almost) working code:
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.js">
</script>
<script src="https://d3js.org/d3-selection-multi.v0.4.min.js"></script>
<script>
var outerWidth = 500;
var outerheight = 250;
var margin = {
left: -50,
top: 0,
right: -50,
bottom: 0
};
var xColumn = "longitude";
var yColumn = "latitude";
var rColumn = "population";
var peoplePerPixel = 1000000;
var innerWidth = outerWidth - margin.left - margin.right;
var innerHeight = outerheight - margin.top - margin.bottom;
var svg = d3.select("body").append("svg")
.attr("width", outerWidth)
.attr("height", outerheight);
var g = svg.append("g")
.attr("transform", "translate (" + margin.left + "," + margin.top + ")");
var xScale = d3.scaleLinear()
.range([0, innerWidth]);
var yScale = d3.scaleLinear()
.range([innerHeight, 0]);
var rScale = d3.scaleSqrt().range([1, 5]);
function render(data) {
xScale.domain(d3.extent(data, function(d) {
return d[xColumn];
}));
yScale.domain(d3.extent(data, function(d) {
return d[yColumn];
}));
rScale.domain([0, d3.max(data, function(d) {
return d[rColumn];
})]);
var circles = svg.selectAll("circle").data(data);
circles.enter().append("circle").attr("cx", function(d) {
return xScale(d[xColumn]);
})
.attr("cy", function(d) {
return yScale(d[yColumn]);
})
.attr("r", function(d) {
return rScale(d[rColumn]);
});
circles.exit().remove();
}
function type(d) {
d.latitude = +d.latitude;
d.longitude = +d.longitude;
d.population = +d.population;
return d;
}
var data = d3.csv(
"https://raw.githubusercontent.com/Pre60/myTest/master/map_cities.csv",
type, render)
</script>
PS: There is no difference in writing var data = d3.csv(url, callback), since d3.csv doesn't return anything (actually, it returns an object related to the request). So, just drop that var data.

d3 v4 scale returning incorrect values

I am trying to plot a scatter plot with with a variable containing json. I have about 800 points to plot.
This is my of code:
var data = json_games;
var svg = d3.select("svg"),
margin = {top: 30, right: 30, bottom: 30, left: 400},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
data.forEach(function(d) {
d.Component1 = +d.Component1;
d.Component2 = +d.Component2;
});
var x = d3.scaleLinear().range([0, width]).domain([d3.min(data, function(d) { return d.Component1; }),d3.max(data, function(d) { return d.Component1; })]);
var y = d3.scaleLinear().range([0, height]).domain([d3.min(data, function(d) { return d.Component2; }),d3.max(data, function(d) { return d.Component2; })]);
// Add the scatterplot
g.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function(d) {
return x(d.Component1); })
.attr("cy", function(d) {
return y(d.Component2); });
// Add the X Axis
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add the Y Axis
g.append("g")
.call(d3.axisLeft(y));
As the data is huge in order to find the maximum and minimum values of x and y components I used cgrome console and the values that I am getting are as follows:
>d3.min(data, function(d) { return d.Component1; })
>-0.20829495230931433
>d3.max(data, function(d) { return d.Component1; })
>0.35130959917777926
>d3.min(data, function(d) { return d.Component2; })
>-1.2035701018868445
>d3.max(data, function(d) { return d.Component2; })
>0.7208057297018022
and the scaled values of x and y that I am getting are:
x(0.6)
>1169.967094854204
y(0.6)
>468.6117109457583
Because of this the points in the scatterplot are being drawn in corners.
Can someone please help. I also tried d3.extent but with the same values.
Any help will be highly appreciated.

d3js updates only once

I have a visualization task that I need to make it done with d3.js. Here's my code.
var w = 700;
var h = 500;
var offset = 100;
var padding = 20;
var colors = d3.scale.category10();
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var texts = function(ds,ds2){
var stack = d3.layout.stack();
stack_data = stack(ds);
var xScale = d3.scale.ordinal()
.domain(d3.range(ds[0].length))
.rangeRoundBands([0, w-offset], 0.50);
var yScale = d3.scale.linear()
.domain([0,
d3.max(stack_data, function(d) {
return d3.max(d, function(d) {
return d.y0 + d.y -20;
});
})
])
.range([padding, h-50]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(ds[0].length);
gs = svg.selectAll("g").data(stack_data);
for (var i5 = 0; i5 < ds.length; i5++) {
gs.enter()
.append("g")
.attr("class", "stacked_bars")
.attr("fill", function(d, i) {
return colors(i);
});
asd = gs.selectAll("rect").data(function(d) { return d; });
asd.enter().append("rect");
asd.transition()
.duration(1000)
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d.y0) - yScale(d.y);
})
.attr("height", function(d) {
return yScale(d.y);
})
.attr("width", xScale.rangeBand())
.attr("class", "rectbar");
};
gs.append("g") // add a group element to the svg
.attr("class", "axis") //Assign class "axis" to group
.attr("transform", "translate(0," + (h - padding) + ")") // shift the axis to bottom
.call(xAxis); // call the axis function
gs.exit().remove();
}
res = dataGenerator("Europe");
dataset = res[0];
dataset2 = res[1];
texts(dataset,dataset2);
d3.select("#selector").on("change", function() {
cont = d3.select(this).property('value');
res = dataGenerator(cont)
dataset = res[0]
dataset2 = res[1]
//svg.selectAll(".sym").remove()
texts(dataset,dataset2);
});
It basically gets the data and generates stacked bars. When user uses the select element on the page, it updates the data and generates new results. It successfully gets the first results and when user selects another option, it makes it happen also. But when user tries to use select part once again. It only generates bars for dataset's first item.
So, in this particular case I have countries and their data as numbers, at first load and first update it successfully shows all but when it comes to second update, it only generate bars for first country in dataset. It's been hours that I'm trying to fix this. I know I only have a little mistake but couldn't make it to solve.
Also here's the jsfiddle of the code: https://jsfiddle.net/510ep9ux/4/
Since I'm new at d3.js, I may not understand the update concept well.
So, any guesses?
Solved, using two separate functions textsInit and textsUpdate :
https://jsfiddle.net/qxqdp36x/2/
Essentially you need to separate initialization and update logic, and avoid re-creating elements when updating, that causes unintended behaviours.
Also, the variables gs and asd needs to be global to be accessible to both functions.
var textsInit = function(ds, ds2) {
var stack = d3.layout.stack();
stack_data = stack(ds);
var xScale = d3.scale.ordinal()
.domain(d3.range(ds[0].length))
.rangeRoundBands([0, w - offset], 0.50);
var yScale = d3.scale.linear()
.domain([0,
d3.max(stack_data, function(d) {
return d3.max(d, function(d) {
return d.y0 + d.y - 20;
});
})
])
.range([padding, h - 50]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(ds[0].length);
gs = svg.selectAll("g").data(stack_data);
bars = gs.enter();
bars.append("g")
.attr("class", "stacked_bars")
.attr("fill", function(d, i) {
return colors(i);
});
asd = gs.selectAll("rect").data(function(d) {
return d;
});
asd.enter().append("rect");
asd.transition()
.duration(1000)
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d.y0) - yScale(d.y);
})
.attr("height", function(d) {
return yScale(d.y);
})
.attr("width", xScale.rangeBand())
.attr("class", "rectbar");
gs.append("g") // add a group element to the svg
.attr("class", "axis") //Assign class "axis" to group
.attr("transform", "translate(0," + (h - padding) + ")") // shift the axis to bottom
.call(xAxis); // call the axis function
}
And:
var textsUpdate = function(ds, ds2) {
var stack = d3.layout.stack();
stack_data = stack(ds);
var xScale = d3.scale.ordinal()
.domain(d3.range(ds[0].length))
.rangeRoundBands([0, w - offset], 0.50);
var yScale = d3.scale.linear()
.domain([0,
d3.max(stack_data, function(d) {
return d3.max(d, function(d) {
return d.y0 + d.y - 20;
});
})
])
.range([padding, h - 50]);
gs.data(stack_data);
asd = gs.selectAll("rect").data(function(d) { return d; });
asd.transition()
.duration(1000)
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d.y0) - yScale(d.y);
})
.attr("height", function(d) {
return yScale(d.y);
})
.attr("width", xScale.rangeBand())
.attr("class", "rectbar");
}
Edited to fix a small bug, updating the asd selection's data.
I made 2 simple but crucial changes to your code.
https://jsfiddle.net/guanzo/510ep9ux/6/
From
gs = svg.selectAll("g").data(stack_data);
to
gs = svg.selectAll("g.stacked_bars").data(stack_data);
The axis is also contained in a g element, so you have to ensure you're only selecting elements that are used for your data, and not unrelated elements.
From
gs.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
to
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
If you go into the browser inspector you'll see that you have an axis element for EVERY stacked_bars element, you only need 1 obviously. It only looks like there's 1 axis because they're absolutely positioned and stacked on top of each other.
I changed it so that the axis is appended when the svg is created, and every time new data is selected, the axis will update itself.

Trying to transfer Tributary D3.js example into JSFiddle

I'm rather a beginner at both JS and D3.js; my JSFiddle is here.
JSHint shows no errors, so I think I'm doing the D3 wrong.
I'm trying to do the same thing as in these questions, adapting a Tributary example to run outside of that platform: "Exporting" a Tributary example that makes use of the tributary object - d3.js and Getting horizontal stack bar example to display using d3.js (I'm even adapting the same code as the latter) Unfortunately, there is no corrected JSFiddle or other example in either answer
Here's my code:
var VanillaRunOnDomReady = function() {
var margins = {
top: 12,
left: 48,
right: 24,
bottom: 24
};
var data = [
{"key":"Nonviolent", "cat1":0.69, "cat2":0.21, "cat3":0.10},
{"key":"Violent", "cat1":0.53, "cat2":0.29, "cat3":0.18}
];
var catnames = {cat1: "No mental illness",
cat2: "Mild mental illness",
cat3: "Moderate or severe mental illness"};
var svg = d3.select('body')
.append('svg')
.attr('width', width + margins.left + margins.right)
.attr('height', height + margins.top + margins.bottom)
.append('g')
.attr('transform', 'translate(' + margins.left + ',' + margins.top + ')');
var n = 3, // number of layers
m = data.length, // number of samples per layer
stack = d3.layout.stack(),
labels = data.map(function(d) {return d.key;}),
//go through each layer (cat1, cat2 etc, that's the range(n) part)
//then go through each object in data and pull out that objects's catulation data
//and put it into an array where x is the index and y is the number
layers = stack(d3.range(n).map(function(d) {
var a = [];
for (var i = 0; i < m; ++i) {
a[i] = {x: i, y: data[i]['cat' + (d+1)]};
}
return a;
})),
//the largest single layer
yGroupMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y; }); }),
//the largest stack
yStackMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); });
var margin = {top: 40, right: 10, bottom: 20, left: 50},
width = 677 - margin.left - margin.right,
height = 533 - margin.top - margin.bottom;
var y = d3.scale.ordinal()
.domain(d3.range(m))
.rangeRoundBands([2, height], 0.08);
var x = d3.scale.linear()
.domain([0, yStackMax])
.range([0, width]);
var color = d3.scale.linear()
.domain([0, n - 1])
.range(["#aad", "#556"]);
var layer = svg.selectAll(".layer")
.data(layers)
.enter().append("g")
.attr("class", "layer")
.style("fill", function(d, i) { return color(i); });
layer.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("y", function(d) { return y(d.x); })
.attr("x", function(d) { return x(d.y0); })
.attr("height", y.rangeBand())
.attr("width", function(d) { return x(d.y); });
var yAxis = d3.svg.axis()
.scale(y)
.tickSize(1)
.tickPadding(6)
.tickValues(labels)
.orient("left");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
};
I think you are just missing a (); at the end of your function and before the semicolon. That would make it self executing. I forked your fiddle.
var VanillaRunOnDomReady = function() {
var margins = {
top: 12,
left: 48,
right: 24,
bottom: 24
};
var data = [
{"key":"Nonviolent", "cat1":0.69, "cat2":0.21, "cat3":0.10},
{"key":"Violent", "cat1":0.53, "cat2":0.29, "cat3":0.18}
];
var catnames = {cat1: "No mental illness",
cat2: "Mild mental illness",
cat3: "Moderate or severe mental illness"};
var svg = d3.select('body')
.append('svg')
.attr('width', width + margins.left + margins.right)
.attr('height', height + margins.top + margins.bottom)
.append('g')
.attr('transform', 'translate(' + margins.left + ',' + margins.top + ')');
var n = 3, // number of layers
m = data.length, // number of samples per layer
stack = d3.layout.stack(),
labels = data.map(function(d) {return d.key;}),
//go through each layer (cat1, cat2 etc, that's the range(n) part)
//then go through each object in data and pull out that objects's catulation data
//and put it into an array where x is the index and y is the number
layers = stack(d3.range(n).map(function(d) {
var a = [];
for (var i = 0; i < m; ++i) {
a[i] = {x: i, y: data[i]['cat' + (d+1)]};
}
return a;
})),
//the largest single layer
yGroupMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y; }); }),
//the largest stack
yStackMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); });
var margin = {top: 40, right: 10, bottom: 20, left: 50},
width = 677 - margin.left - margin.right,
height = 533 - margin.top - margin.bottom;
var y = d3.scale.ordinal()
.domain(d3.range(m))
.rangeRoundBands([2, height], 0.08);
var x = d3.scale.linear()
.domain([0, yStackMax])
.range([0, width]);
var color = d3.scale.linear()
.domain([0, n - 1])
.range(["#aad", "#556"]);
var svg = d3.select("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 layer = svg.selectAll(".layer")
.data(layers)
.enter().append("g")
.attr("class", "layer")
.style("fill", function(d, i) { return color(i); });
layer.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("y", function(d) { return y(d.x); })
.attr("x", function(d) { return x(d.y0); })
.attr("height", y.rangeBand())
.attr("width", function(d) { return x(d.y); });
var yAxis = d3.svg.axis()
.scale(y)
.tickSize(1)
.tickPadding(6)
.tickValues(labels)
.orient("left");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
}();

Categories