d3 donut chart transistion change - d3.js

Another d3 newbie question here.
I am trying to transition change a donut chart with grouped nested data. Here's what I have now.
http://bricbracs.com/test/
So when I click on a segment arc like New York it will update with data from the dept column with a nested function so I get this. I am close. I have the data grouped. I need help redrawing the donut.
http://bricbracs.com/test1/
Here is a csv file.
status,dept,city,points
temp,finance,New York,33
contract,HR,London,12
contract,HR,New York,11
casual,shop,London,43
contract,shop,Paris,51
temp,finance,London,7
contract,office,New York,61
contract,shop,London,31
temp,office,New York,16
contract,office,London,19
temp,finance,London,7
contract,office,New York,61
contract,sales,London,31
temp,finance,New York,16
contract,sales,Paris,19
Here is the d3 script. Thanks in advance.
<script>
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.category20();
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(radius - 70);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) {
return d.values;
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
svg.style("cursor","pointer")
d3.csv("data.csv", function(error, data) {
var data = d3.nest()
.key(function(d) {
return d.city;
})
.rollup(function(d) {
return d3.sum(d, function(g) {
return g.points;
});
}).entries(data);
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.attr("stroke", "white")
.attr("stroke-width", 0.5)
.style("fill", function(d) {
return color(d.data.key);
})
.on("mouseover", function (d) {
d3.select("#tooltip")
.style("left", d3.event.pageX + "px")
.style("top", d3.event.pageY + "px")
.style("opacity", .75)
.select("#value")
.text(d.value.toLocaleString())
document.getElementById("demo").innerHTML =d.data.key
})
.on("mouseout", function () {
d3.select("#tooltip")
.style("opacity", 0);
console.log("OUT")
})
.on("mousemove", function () {
d3.select("#tooltip")
.style("left", (d3.event.pageX +20) + "px")
.style("top", d3.event.pageY + "px+50")
})
.on("click", function() {
change()
});
g.append("text")
.attr("transform", function(d) {
var c = arc.centroid(d),
x = c[0],
y = c[1],l
h = Math.sqrt(x*x + y*y);
return "translate(" + arc.centroid(d) + ")";
})
//.attr("dy", "1em")
.style("text-anchor", "middle")
.text(function(d) {
return d.data.key
})
function change() {
var data = d3.nest()
.key(function(d) {
return d.dept;
})
.rollup(function(d) {
return d3.sum(d, function(g) {
return g.points;
});
}).entries(data);
var path = svg.selectAll("path");
path = path.data(pie(data), function(d) { return d.data.key; })
path.enter().append("path").attr("fill", function(d) {return color(d.data.key); })
path.exit().remove()
path.attr("d", arc)
}
});

Related

D3 V4 Rect bind data in stacked bar chart

In Normalized stacked bar I am trying to bind data in all rect in a bar but wrong value is passed. I adopted my code from this example and made it horizontal. Below is my code and I have created a plunker as well. In .text function entire object is passed. Can someone help me where I am going wrong
var svg = d3.select("svg"),
margin = {
top: 20,
right: 60,
bottom: 30,
left: 40
},
/*width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,*/
width = 120,
height = 120,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var y = d3.scaleBand()
.rangeRound([0, width])
.padding(0.1)
.align(0.1);
var x = d3.scaleLinear()
.rangeRound([height, 0]);
var z = d3.scaleOrdinal()
.range(['#02CA22', '#FB5652', '#FFB005']);
var stack = d3.stack()
.offset(d3.stackOffsetExpand);
d3.csv("data.csv", type, function (error, data) {
if (error) throw error;
/*data.sort(function(a, b) {
return b[data.columns[1]] / b.total - a[data.columns[1]] / a.total;
});*/
y.domain(data.map(function (d) {
return d.State;
}));
z.domain(data.columns.slice(1));
var serie = g.selectAll(".serie")
.data(stack.keys(data.columns.slice(1))(data))
.enter().append("g")
.attr("class", "serie")
.attr("fill", function (d) {
return z(d.key);
});
var rect = serie.selectAll("rect")
.data(function (d) {
return d;
}).enter();
rect.append("rect")
.attr("y", function (d) {
return y(d.data.State);
})
.attr("x", function (d) {
return x(d[1]);
})
.attr("width", function (d) {
return x(d[0]) - x(d[1]);
})
.attr("height", y.bandwidth());
rect.append("text")
.text(function (d) {
console.log('d');
console.log(d);
console.log(d.data.key);
return 'val';
})
.attr("y", function (d) { return y(d.data.State) + y.bandwidth() / 2; })
.attr("x", function (d) {
return x(d[1]);
});
/* g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).ticks(2, "%"));*/
g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y));
var legend = serie.append("g")
.attr("class", "legend")
.attr("transform", function (d) {
var d = d[0];
return "translate(" + ((x(d[0]) + x(d[1])) / 2) + ", " + (y(d.data.State) - y.bandwidth()) + ")";
});
/*legend.append("line")
.attr("y1", 5)
.attr("x1", 15)
.attr("x2", 15)
.attr("y2", 12)
.attr("stroke", "#000");
legend.append("text")
.attr("x", 9)
.attr("dy", "0.35em")
.attr("fill", "#000")
.style("font", "10px sans-serif")
.text(function (d) {
return d.key;
}); */
});
function type(d, i, columns) {
var t;
for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
d.total = t;
return d;
}
I think the best way to do this is to modify your subselection data-binding to include that information:
var rect = serie.selectAll("rect")
.data(function (d) {
// return all the data you need as flat as possible
var rv = d.map(function(da){
return {p: da, key: d.key, state: da.data.State}
});
return rv;
}).enter();
The text is then available as:
rect.append("text")
.text(function (d) {
return d.key;
})
.attr("y", function (d) { return y(d.state) + y.bandwidth() / 2; })
.attr("x", function (d) {
return x(d.p[1]);
});
Updated Plunker.

Set arbitrary center in streamgraph offset

I have data in a streamgraph stack layout and the desired aesthetic I'm after is to assign an arbitrary series as the center line(s). Series above those lines (as determined by their index in the data) will stack on top and series below that line will stack below.
Here's a jsFidde.
In this example, I'd like the MS and the RC series to be single horizontal lines with the other groups stacked above and below them, respectively. (As opposed to the data index, I could also set the middle series based on some data attribute, in this example, oldest date would make sense.)
I think the solution would require passing my own offset function but I'm having a hard time figuring out how the built-in ones do what they do.
HTML
<div class="chart">
JS
// Adapted from https://gist.github.com/WillTurman/4631136
var data = [
{"key":"DJ","value":0,"date":"1/8/13"},
{"key":"DJ","value":0,"date":"1/9/13"},
{"key":"DJ","value":0,"date":"1/10/13"},
{"key":"DJ","value":1,"date":"1/11/13"},
{"key":"DJ","value":1,"date":"1/12/13"},
{"key":"MS","value":0,"date":"1/8/13"},
{"key":"MS","value":1,"date":"1/9/13"},
{"key":"MS","value":1,"date":"1/10/13"},
{"key":"MS","value":1,"date":"1/11/13"},
{"key":"MS","value":1,"date":"1/12/13"},
{"key":"RC","value":0,"date":"1/8/13"},
{"key":"RC","value":1,"date":"1/9/13"},
{"key":"RC","value":1,"date":"1/10/13"},
{"key":"RC","value":1,"date":"1/11/13"},
{"key":"RC","value":1,"date":"1/12/13"},
{"key":"CG","value":0,"date":"1/8/13"},
{"key":"CG","value":0,"date":"1/9/13"},
{"key":"CG","value":0,"date":"1/10/13"},
{"key":"CG","value":0,"date":"1/11/13"},
{"key":"CG","value":1,"date":"1/12/13"},
{"key":"RI","value":0,"date":"1/8/13"},
{"key":"RI","value":0,"date":"1/9/13"},
{"key":"RI","value":0,"date":"1/10/13"},
{"key":"RI","value":0,"date":"1/11/13"},
{"key":"RI","value":1,"date":"1/12/13"}
]
chart(data, "pink");
var datearray = [];
var colorrange = [];
function chart(data, color) {
if (color == "blue") {
colorrange = ["#045A8D", "#2B8CBE", "#74A9CF", "#A6BDDB", "#D0D1E6", "#F1EEF6"];
}
else if (color == "pink") {
colorrange = ["#980043", "#DD1C77", "#DF65B0", "#C994C7", "#D4B9DA", "#F1EEF6"];
}
else if (color == "orange") {
colorrange = ["#B30000", "#E34A33", "#FC8D59", "#FDBB84", "#FDD49E", "#FEF0D9"];
}
strokecolor = colorrange[0];
var format = d3.time.format("%m/%d/%y");
var margin = {top: 20, right: 40, bottom: 30, left: 30};
var width = document.body.clientWidth - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;
var tooltip = d3.select("body")
.append("div")
.attr("class", "remove")
.style("position", "absolute")
.style("z-index", "20")
.style("visibility", "hidden")
.style("top", "30px")
.style("left", "55px");
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height-10, 0]);
var z = d3.scale.ordinal()
.range(colorrange);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(d3.time.weeks);
var yAxis = d3.svg.axis()
.scale(y);
var yAxisr = d3.svg.axis()
.scale(y);
var stack = d3.layout.stack()
.offset("silhouette")
.values(function(d) { return d.values; })
.x(function(d) { return d.date; })
.y(function(d) { return d.value; });
var nest = d3.nest()
.key(function(d) { return d.key; });
var area = d3.svg.area()
.interpolate("linear")
.x(function(d) { return x(d.date); })
.y0(function(d) { return y(d.y0); })
.y1(function(d) { return y(d.y0 + d.y); });
var svg = d3.select(".chart").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 + ")");
data.forEach(function(d) {
d.date = format.parse(d.date);
d.value = +d.value;
});
var layers = stack(nest.entries(data));
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]);
svg.selectAll(".layer")
.data(layers)
.enter().append("path")
.attr("class", "layer")
.attr("d", function(d) { return area(d.values); })
.style("fill", function(d, i) { return z(i); });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + width + ", 0)")
.call(yAxis.orient("right"));
svg.append("g")
.attr("class", "y axis")
.call(yAxis.orient("left"));
svg.selectAll(".layer")
.attr("opacity", 1)
.on("mouseover", function(d, i) {
svg.selectAll(".layer").transition()
.duration(250)
.attr("opacity", function(d, j) {
return j != i ? 0.6 : 1;
})})
.on("mousemove", function(d, i) {
mousex = d3.mouse(this);
mousex = mousex[0];
var invertedx = x.invert(mousex);
invertedx = invertedx.getMonth() + invertedx.getDate();
var selected = (d.values);
for (var k = 0; k < selected.length; k++) {
datearray[k] = selected[k].date
datearray[k] = datearray[k].getMonth() + datearray[k].getDate();
}
mousedate = datearray.indexOf(invertedx);
pro = d.values[mousedate].value;
d3.select(this)
.classed("hover", true)
.attr("stroke", strokecolor)
.attr("stroke-width", "0.5px"),
tooltip.html( "<p>" + d.key + "<br>" + pro + "</p>" ).style("visibility", "visible");
})
.on("mouseout", function(d, i) {
svg.selectAll(".layer")
.transition()
.duration(250)
.attr("opacity", "1");
d3.select(this)
.classed("hover", false)
.attr("stroke-width", "0px"), tooltip.html( "<p>" + d.key + "<br>" + pro + "</p>" ).style("visibility", "hidden");
})
var vertical = d3.select(".chart")
.append("div")
.attr("class", "remove")
.style("position", "absolute")
.style("z-index", "19")
.style("width", "1px")
.style("height", "380px")
.style("top", "10px")
.style("bottom", "30px")
.style("left", "0px")
.style("background", "#fff");
d3.select(".chart")
.on("mousemove", function(){
mousex = d3.mouse(this);
mousex = mousex[0] + 5;
vertical.style("left", mousex + "px" )})
.on("mouseover", function(){
mousex = d3.mouse(this);
mousex = mousex[0] + 5;
vertical.style("left", mousex + "px")});
}

How to rotate and change font size on x axis

I am new to D3 and I am trying to create some charts based on weather (temperature) data. I have created a separate js file with my code so that all the charts are called from one HTML page. However, the x-axis is very cluttered because I have daily data displayed.
Here is the main js file - how do I make the x-axis rotate and insert space between the days to display? Or alternatively, just show each month (April, May, June, etc.) rather than each day?
(function (){
var VIZ = {};
var margin = {top: 20, right: 55, bottom: 50, left: 20},
width = 1000 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d/%m/%Y").parse;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var color = d3.scale.ordinal()
.range(['blue', 'red', 'green','yellow']);
var svg = d3.select("#chart").append("svg")
.attr("id", "thesvg")
.attr("viewBox", "0 0 1000 500")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
function make_x_axis() {
return d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(20)
}
function make_y_axis() {
return d3.svg.axis()
.scale(y)
.orient("left")
.ticks(20)
}
VIZ.stackChart = function (data, offset) {
var stack = d3.layout.stack()
.values(function (d) { return d.values; })
.x(function (d) { return x(d.label) + x.rangeBand() / 2; })
.y(function (d) { return d.value; });
var area = d3.svg.area()
.interpolate("cardinal")
.x(function (d) { return x(d.label) + x.rangeBand() / 2; })
.y0(function (d) { return y(d.y0); })
.y1(function (d) { return y(d.y0 + d.y); });
var labelVar = 'date';
var varNames = d3.keys(data[0])
.filter(function (key) { return key !== labelVar;});
color.domain(varNames);
var seriesArr = [], series = {};
varNames.forEach(function (name) {
series[name] = {name: name, values:[]};
seriesArr.push(series[name]);
});
data.forEach(function (d) {
varNames.map(function (name) {
series[name].values.push({name: name, label: d[labelVar], value: +d[name]});
});
});
x.domain(data.map(function (d) { return d.date; }));
stack.offset(offset)
stack(seriesArr);
y.domain([0, d3.max(seriesArr, function (c) {
return d3.max(c.values, function (d) { return d.y0 + d.y; });
})]);
var selection = svg.selectAll(".series")
.data(seriesArr)
.enter().append("g")
.attr("class", "series");
selection.append("path")
.attr("class", "streamPath")
.attr("d", function (d) { return area(d.values); })
.style("fill", function (d) { return color(d.name); })
.style("stroke", "grey");
var points = svg.selectAll(".seriesPoints")
.data(seriesArr)
.enter().append("g")
.attr("class", "seriesPoints");
points.selectAll(".point")
.data(function (d) { return d.values; })
.enter().append("circle")
.attr("class", "point")
.attr("cx", function (d) { return x(d.label) + x.rangeBand() / 2; })
.attr("cy", function (d) { return y(d.y0 + d.y); })
.attr("r", "10px")
.style("fill",function (d) { return color(d.name); })
.on("mouseover", function (d) { showPopover.call(this, d); })
.on("mouseout", function (d) { removePopovers(); })
drawAxis();
drawLegend(varNames);
}
VIZ.lineChart = function (data) {
var line = d3.svg.line()
.interpolate("linear")
.x(function (d) { return x(d.label) + x.rangeBand() / 2; })
.y(function (d) { return y(d.value); });
var labelVar = 'date';
var varNames = d3.keys(data[0]).filter(function (key) { return key !== labelVar;});
color.domain(varNames);
var seriesData = varNames.map(function (name) {
return {
name: name,
values: data.map(function (d) {
return {name: name, label: d[labelVar], value: +d[name]};
})
};
});
x.domain(data.map(function (d) { return d.date; }));
y.domain([
d3.min(seriesData, function (c) {
return d3.min(c.values, function (d) { return d.value; });
}),
d3.max(seriesData, function (c) {
return d3.max(c.values, function (d) { return d.value; });
})
]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
var series = svg.selectAll(".series")
.data(seriesData)
.enter().append("g")
.attr("class", "series");
series.append("path")
.attr("class", "line")
.attr("d", function (d) { return line(d.values); })
.style("stroke", function (d) { return color(d.name); })
.style("stroke-width", "4px")
.style("fill", "none")
series.selectAll(".linePoint")
.data(function (d) { return d.values; })
.enter().append("circle")
.attr("class", "linePoint")
.attr("cx", function (d) { return x(d.label) + x.rangeBand()/2; })
.attr("cy", function (d) { return y(d.value); })
.attr("r", "5px")
.style("fill", function (d) { return color(d.name); })
.style("stroke", "grey")
.style("stroke-width", "1px")
.on("mouseover", function (d) { showPopover.call(this, d); })
.on("mouseout", function (d) { removePopovers(); })
svg.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(make_x_axis()
.tickSize(-height, 0, 0)
.tickFormat("")
)
svg.append("g")
.attr("class", "grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat("")
)
drawAxis();
drawLegend(varNames);
}
VIZ.stackBarChart = function (data) {
var labelVar = 'date';
var varNames = d3.keys(data[0]).filter(function (key) { return key !== labelVar;});
color.domain(varNames);
data.forEach(function (d) {
var y0 = 0;
d.mapping = varNames.map(function (name) {
return {
name: name,
label: d[labelVar],
y0: y0,
y1: y0 += +d[name]
};
});
d.total = d.mapping[d.mapping.length - 1].y1;
});
x.domain(data.map(function (d) { return d.date; }));
y.domain([0, d3.max(data, function (d) { return d.total; })]);
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", ".15em")
.attr("transform", function(d) {
return "rotate(-65)"
});
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("");
var selection = svg.selectAll(".series")
.data(data)
.enter().append("g")
.attr("class", "series")
.attr("transform", function (d) { return "translate(" + x(d.date) + ",0)"; });
selection.selectAll("rect")
.data(function (d) { return d.mapping; })
.enter().append("rect")
.attr("width", x.rangeBand())
.attr("y", function (d) { return y(d.y1); })
.attr("height", function (d) { return y(d.y0) - y(d.y1); })
.style("fill", function (d) { return color(d.name); })
.style("stroke", "grey")
.on("mouseover", function (d) { showPopover.call(this, d); })
.on("mouseout", function (d) { removePopovers(); })
drawAxis();
drawLegend(varNames);
}
VIZ.clearAll = function () {
svg.selectAll("*").remove()
}
function drawAxis() {
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.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("Maximum Temperature");
}
function drawLegend (varNames) {
var legend = svg.selectAll(".legend")
.data(varNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d, i) { return "translate(55," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 10)
.attr("width", 10)
.attr("height", 10)
.style("fill", color)
.style("stroke", "grey");
legend.append("text")
.attr("x", width - 12)
.attr("y", 6)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function (d) { return d; });
}
function removePopovers () {
$('.popover').each(function() {
$(this).remove();
});
}
function showPopover (d) {
$(this).popover({
title: d.name,
placement: 'auto top',
container: 'body',
trigger: 'manual',
html : true,
content: function() {
return "Date: " + d.label +
"<br/>Temperature: " + d3.format(",")(d.value ? d.value: d.y1 - d.y0); }
});
$(this).popover('show')
}
VIZ.onResize = function () {
var aspect = 1000 / 500, chart = $("#thesvg");
var targetWidth = chart.parent().width();
chart.attr("width", targetWidth);
chart.attr("height", targetWidth / aspect);
}
window.VIZ = VIZ;
}())
You can rotate texts in x axis using transform attribute.
svg.select(".x.axis")
.selectAll("text")
.attr("transform"," translate(0,15) rotate(-65)"); // To rotate the texts on x axis. Translate y position a little bit to prevent overlapping on axis line.
.style("font-size","15px"); //To change the font size of texts
Use tickformat function of d3 scale for date formatting. To display only month from date, you can use the code below.
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom')
.tickFormat(d3.time.format('%B'));
Update:
I think, it would be better if you reduce the number of ticks using ticks method to make texts readable.
xAxis.ticks(d3.time.day, 20);
You can refer more about d3 svg axis from here and about time formats from here
I guess things must have changed since the original answer was posted in 2014. In any case, in D3.js versions 5 and up, the mentioned selection code no longer works.
Since the structure of the tick is now a group, for example:
<g class="tick" opacity="1" transform="translate(0.5,0)">
<line stroke="currentColor" y2="6"></line>
<text fill="currentColor" y="9" dy="0.71em">0.0</text>
</g>
...
The selection code needs to be modified like this:
svg.select(".x.axis")
.selectAll(".tick text")
...

Labels for Animated Donut Chart D3

I am trying to label my animated Donut using D3...Can change data and get the drop-down to work but am having trouble labeling the donuts....Here is my code
var radius = 74,
padding = 10;
var color = d3.scale.ordinal()
.range(["#aec7e8", "#ff7f0e", "#2ca02c", "#bdbdbd", "#8c564b", "#d62728", "#17becf", "#7f7f7f", "#bcbd22", "#393b79","#31a354"]);
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius - 50);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
d3.csv("data.csv", function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "State"; }));
data.forEach(function(d) {
d.DataUnitID = color.domain().map(function(name) {
return {name: name, population: +d[name]};
});
});
var legend = d3.select("body").append("svg")
.attr("class", "legend")
.attr("width", radius * 2)
.attr("height", radius * 3.5)
.selectAll("g")
.data(color.domain().slice().reverse())
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("width", 18)
.attr("height", 16)
.style("fill", color);
legend.append("text")
.attr("x", 24)
.attr("y", 9)
.attr("dy", ".35em")
.text(function(d) { return d; });
var svg = d3.select("body").selectAll(".pie")
.data(data)
.enter().append("svg")
.attr("class", "pie")
.attr("width", radius * 2)
.attr("height", radius * 2)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
svg.selectAll(".arc")
.data(function(d) { return pie(d.DataUnitID); })
.enter().append("path")
.attr("class", "arc")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.name); });
svg.append("text")
.attr("dy", ".15em")
.style("text-anchor", "middle")
.text(function(d) { return d.State; });
});

Create Paired Bar Chart d3.js

I need help adding a second series of data to my bar chart. Currently I'm populating the bars from the glob key in my dataset. This will be the first series. The second series I would like to be is local.
How do I go about adding that?
Play with my JSFiddle here.
var w = 300;
var h = 200;
var colors = ["#377EB8", "#4DAF4A"];
var dataset = [
{"keyword": "payday loans", "glob": 1500000, "local": 673000, "cpc": "14.11"},
{"keyword": "title loans", "glob": 165000, "local": 165000, "cpc": "12.53" },
{"keyword": "personal loans", "glob": 550000, "local": 301000, "cpc": "6.14"}
];
var data = [[1500000, 165000, 550000],
[673000, 165000, 301000]];
var tdata = d3.transpose(dataset.glob, dataset.local);
var series = 2; // Global & Local
var x0Scale = d3.scale.ordinal()
.domain(d3.range(dataset.length))
.rangeRoundBands([0, w], 0.05);
var x1Scale = d3.scale.ordinal()
.domain(d3.range(dataset.length))
.rangeRoundBands([0, w], 0.05);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {return d.glob;})])
.range([0, h]);
var glob = function(d) {
return d.glob;
};
var cpc = function(d) {
return d.cpc;
};
var commaFormat = d3.format(',');
//SVG element
var svg = d3.select("#searchVolume")
.append("svg")
.attr("width", w)
.attr("height", h);
// Graph Bars
svg.selectAll("rect")
.data(dataset, cpc, glob)
.enter()
.append("rect")
.attr("x", function(d, i){
return x0Scale(i);
})
.attr("y", function(d) {
return h - yScale(d.glob);
})
.attr("width", x0Scale.rangeBand())
.attr("height", function(d) {
return yScale(d.glob);
})
.attr("fill", colors[1])
.on("mouseover", function(d) {
//Get this bar's x/y values, then augment for the tooltip
var xPosition = parseFloat(d3.select(this).attr("x")) + x0Scale.rangeBand() / 3;
var yPosition = parseFloat(d3.select(this).attr("y")) + yScale;
//Update Tooltip Position & value
d3.select("#tooltip")
.style("left", xPosition + "px")
.style("top", yPosition + "px")
.select("#cpcVal")
.text(d.cpc);
d3.select("#tooltip").classed("hidden", false);
})
.on("mouseout", function() {
//Remove the tooltip
d3.select("#tooltip").classed("hidden", true);
});
//Create labels
svg.selectAll("text")
.data(dataset, glob)
.enter()
.append("text")
.text(function(d) {
return commaFormat(d.glob);
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return x0Scale(i) + x0Scale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d.glob) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
It's easiest to create an svg group (<g>) element for each set of data, and then add the individual parts to each group. For example, roughly:
http://jsfiddle.net/WXMwv/1/
var sets = svg.selectAll(".set")
.data(dataset)
.enter().append("g")
.attr("class","set")
.attr("transform",function(d,i){
return "translate(" + x0Scale(i) + ",0)"
})
.on("mouseover", function(d,i) {
//Create x value from data index
var xPosition = parseFloat(x0Scale(i) + x0Scale.rangeBand() / 6);
var yPosition = 0;
//Update Tooltip Position & value
d3.select("#tooltip")
.style("left", xPosition + "px")
.style("top", yPosition + "px")
.select("#cpcVal")
.text(d.cpc);
d3.select("#tooltip").classed("hidden", false);
})
.on("mouseout", function() {
//Remove the tooltip
d3.select("#tooltip").classed("hidden", true);
});
sets.append("rect")
.attr("class","glob")
.attr("width", x0Scale.rangeBand()/2)
.attr("y", function(d) {
return yScale(d.glob);
})
.attr("height", function(d){
return h - yScale(d.glob);
})
.attr("fill", colors[1])
sets.append("rect")
.attr("class","local")
.attr("width", x0Scale.rangeBand()/2)
.attr("y", function(d) {
return yScale(d.local);
})
.attr("x", x0Scale.rangeBand()/2)
.attr("height", function(d){
return h - yScale(d.local);
})
.attr("fill", colors[0])
The text elements are left as an exercise for the reader :)

Resources