The following url is going to get horizontally-oriented tree.
My requirement is however to get a vertically-oriented tree using d3.
Please suggest a proper valid solution for this requirement.
d3js Tree square
I know its been a while since you asked the question, but just in case I would like to bring to your attention a diagram that I made:
The code in on codepen. If you have any questions regarding the code, please let me know.
change line 35, line 56 and elbow function to
<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font-family: "Helvetica Neue", Helvetica, sans-serif;
}
.name {
font-weight: bold;
}
.about {
fill: #777;
font-size: smaller;
}
.link {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="http://d3js.org/d3.v2.min.js?2.9.4"></script>
<script>
var margin = {top: 0, right: 0, bottom: 320, left: 0},
width = 960- margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var tree = d3.layout.tree()
.separation(function(a, b) { return a.parent === b.parent ? 1 : .5; })
.children(function(d) { return d.parents; })
.size([width, height]);
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 + ")");
d3.json("tree.json", function(json) {
var nodes = tree.nodes(json);
var link = svg.selectAll(".link")
.data(tree.links(nodes))
.enter().append("path")
.attr("class", "link")
.attr("d", elbow);
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
node.append("text")
.attr("class", "name")
.attr("x", 8)
.attr("y", -6)
.text(function(d) { return d.name; });
node.append("text")
.attr("x", 8)
.attr("y", 8)
.attr("dy", ".71em")
.attr("class", "about lifespan")
.text(function(d) { return d.born + "–" + d.died; });
node.append("text")
.attr("x", 8)
.attr("y", 8)
.attr("dy", "1.86em")
.attr("class", "about location")
.text(function(d) { return d.location; });
});
function elbow(d, i) {
console.log(d)
return "M" + d.source.x + "," + d.source.y
+ "V" + d.target.y + "H" + d.target.x
+ (d.target.children ? "" : ("v" + margin.bottom))
}
</script>
</body>
this my result
Related
I am trying to create a slider which reveals data as you slide the bar across from left to right. When I slide from right to left, my data does not show up. And secondly, the highest number the x-axis scales to is 9. I have played around with my data, if I put 8 as the highest value for the x-axis, 8 will be the highest value. But I cannot go beyond 9 for some reason. And not all my data displays even if I have all the numbers under 9.
In my data, I have two columns. One called "ep" (this is for the x-axis), and the other called "char" (this is for the y-axis).
Any ideas on how I can get the x-axis to scale properly and have my data show up?
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>LD V6</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body {
font-family:"avenir next", Arial, sans-serif;
font-size: 12px;
color: #696969;
}
.ticks {
font-size: 10px;
}
.track,
.track-inset,
.track-overlay {
stroke-linecap: round;
}
.track {
stroke: #000;
stroke-opacity: 0.3;
stroke-width: 10px;
}
.track-inset {
stroke: #dcdcdc;
stroke-width: 8px;
}
.track-overlay {
pointer-events: stroke;
stroke-width: 50px;
stroke: transparent;
cursor: crosshair;
}
.handle {
fill: #fff;
stroke: #000;
stroke-opacity: 0.5;
stroke-width: 1.25px;
}
</style>
</head>
<body>
<div id="vis">
</div>
<script>
var margin = {top:50, right:30, bottom:30, left:30},
width = 960 - margin.left - margin.right,
height = 600 - margin.top - margin.bottom;
var svg = d3.select("#vis")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
////////// slider //////////
var moving = false;
var currentValue = 0;
var targetValue = 200;
var playButton = d3.select("#play-button");
var x = d3.scaleLinear().range([0, width])
.clamp(true);
var y = d3.scaleLinear().range([height, 0]);
var slider = svg.append("g")
.attr("class", "slider")
.attr("transform", "translate(" + 50 + "," + (height) + ")");
slider.append("line")
.attr("class", "track")
.attr("x1", x.range()[0])
.attr("x2", x.range()[1])
.select(function() { return this.parentNode.appendChild(this.cloneNode(true)); })
.attr("class", "track-inset")
.select(function() { return this.parentNode.appendChild(this.cloneNode(true)); })
.attr("class", "track-overlay")
.call(d3.drag()
.on("start.interrupt", function() { slider.interrupt(); })
.on("start drag", function() {
currentValue = d3.event.x;
update(x.invert(currentValue));
})
);
//Attributes of the slider
slider.insert("g", ".track-overlay")
.attr("class", "ticks")
.attr("transform", "translate(0," + 18 + ")")
/* .selectAll("text")
.data(x.ticks(8))
.enter()
.append("text")
.attr("x", x)
.attr("y", 10)
.attr("text-anchor", "middle")
.text(function(d) { return d.ep); }); */
//Attributes of the slider handle
var handle = slider.insert("circle", ".track-overlay")
.attr("class", "handle")
.attr("r", 8);
/*
var label = slider.append("text")
.attr("class", "label")
.attr("text-anchor", "middle")
.text(formatDate(startDate))
.attr("transform", "translate(0," + (-25) + ")")
*/
////////// plot //////////
var dataset;
var plot = svg.append("g")
.attr("class", "plot")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("trial_v3.csv", prepare, function(data) {
dataset = data;
drawPlot(dataset);
// scale the range of the data
y.domain([0, d3.max(data, function(d) { return d.char; })]);
x.domain([0, d3.max(data, function(d) { return d.ep; })]);
// add the Y Axis
svg.append("g")
.call(d3.axisLeft(y))
.attr("transform", "translate(" + 50 + ",0)");
// add the X Axis
svg.append("g")
.call(d3.axisBottom(x))
.attr("transform", "translate(" + 50 +"," + height + ")")
})
function prepare(d) {
d.ep = d.ep;
d.char = d.char;
return d;
}
function drawPlot(data) {
var locations = plot.selectAll(".location")
.data(data);
// if filtered dataset has more circles than already existing, transition new ones in
locations.enter()
.append("circle")
.attr("class", "location")
.attr("cx", function(d) { return x(d.ep); })
.attr("cy", function(d){ return y(d.char)})
.style("opacity", 0.5)
.attr("r", 5)
.transition()
.duration(1200)
.attr("r", 11
);
// if filtered dataset has less circles than already existing, remove excess
locations.exit()
.remove();
}
function update(h) {
// update position and text of label according to slider scale circle
handle.attr("cx", x(h));
/*label
.attr("x", x(h))
.text(formatDate(h)); */
// filter data set and redraw plot
var newData = dataset.filter(function(d) {
return d.ep < h;
})
drawPlot(newData);
};
/////////////////////////////////////////////////// SVG 2 /////////////////////////////////////////////
/*
var svg2 = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
svg2.append("rect")
.attr("width", 50)
.attr("height",50)
*/
</script>
</body>
Note In this question, I asked how to add a distribution line to the chart.
This is my current status:
I don’t quite understand how to plot two distributions curves for the histograms. Like this:
This is my code (using D3.js version 4):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.bar1 rect {
fill: rgba(0,0,255,0.6);
}
.bar1:hover rect{
fill: rgba(0,0,255,0.9);
}
.bar1 text {
fill: #fff;
font: 10px sans-serif;
}
.bar2 rect {
fill: rgba(255,0,0,0.6);
}
.bar2:hover rect{
fill: rgba(255,0,0,0.9);
}
.bar2 text {
fill: #fff;
font: 10px sans-serif;
}
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
function draw(data) {
var allCongruentData = data.map(function(e){ return e.Congruent;});
var allIncongruentData = data.map(function(e){ return e.Incongruent;});
var formatCount = d3.format(",.0f");
var svg = d3.select("svg"),
margin = {top: 10, right: 30, bottom: 30, left: 30},
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 + ")");
var x = d3.scaleLinear()
.rangeRound([0, width])
.domain([8, 36]);
var bins1 = d3.histogram()
.domain(x.domain())
.thresholds(x.ticks(40))
(allCongruentData);
// var curve = d3.line()
// .x(function(d) { return ???; })
// .y(function(d) { return y(d.Congruent); })
// .curve(d3.curveCatmullRom.alpha(0.5));
var bins2 = d3.histogram()
.domain(x.domain())
.thresholds(x.ticks(40))
(allIncongruentData);
var y = d3.scaleLinear()
.domain([0, d3.max(bins1, function(d) { return d.length; })])
.range([height, 0]);
var bar1 = g.selectAll(".bar1")
.data(bins1)
.enter().append("g")
.attr("class", "bar1")
.attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; });
bar1.append("rect")
.attr("x", 0.5)
.attr("width", x(bins1[0].x1) - x(bins1[0].x0) - 1)
.attr("height", function(d) { return height - y(d.length); });
var bar2 = g.selectAll(".bar2")
.data(bins2)
.enter().append("g")
.attr("class", "bar2")
.attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; });
bar2.append("rect")
.attr("x", 0.5)
.attr("width", x(bins2[0].x1) - x(bins2[0].x0) - 1)
.attr("height", function(d) { return height - y(d.length); });
bar1.append("text")
.attr("dy", ".75em") // why?
.attr("y", 6)
.attr("x", (x(bins1[0].x1) - x(bins1[0].x0)) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.length); });
bar2.append("text")
.attr("dy", ".75em") // why?
.attr("y", 6)
.attr("x", (x(bins2[0].x1) - x(bins2[0].x0)) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.length); });
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
var legend = svg.append("g")
.attr("class", "legend")
.attr("transform", "translate(" + (width - 245) + "," + 40 + ")")
.selectAll("g")
.data(["Congruent", "Incongruent"])
.enter().append("g");
legend.append("text")
.attr("y", function(d, i) {
return i * 30 + 5;
})
.attr("x", 200)
.text(function(d) {
return d;
});
legend.append("rect")
.attr("y", function(d, i) {
return i * 30 - 8;
})
.attr("x", 167)
.attr("width", 20)
.attr("height", 20)
.attr("fill", function(d) {
if (d == "Congruent") {
return 'rgba(0,0,255,0.6';
} else {
return 'rgba(255,0,0,0.6';
}
});
// g.append("path")
// .datum(data)
// .attr("d", line);
}
</script>
</head>
<body>
<h1>Stroop Test</h1>
<svg width="960" height="500"></svg>
<script type="text/javascript">
d3.csv("stroopdata.csv", function(d) {
d.Congruent = +d.Congruent;
d.Incongruent = +d.Incongruent;
return d;
}, draw);
</script>
</body>
</html>
The data looks like this:
Congruent,Incongruent
12.079,19.278
16.791,18.741
9.564,21.214
8.630,15.687
14.669,22.803
12.238,20.878
14.692,24.572
8.987,17.394
9.401,20.762
14.480,26.282
22.328,24.524
15.298,18.644
15.073,17.510
16.929,20.330
18.200,35.255
12.130,22.158
18.495,25.139
10.639,20.429
11.344,17.425
12.369,34.288
12.944,23.894
14.233,17.960
19.710,22.058
16.004,21.157
Any help appreciated.
Hi I'm trying to get the mouseover function work for my line chart so I can hover over the line chart and see the values of each point. I tried using the mouse function but it didn't work. How can I fix/do this? I also included a picture of the line chart
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Unemployment by Ward Bar Chart</title>
<style type="text/css">
.axis text{
font-family: Arial;
font-size: 13px;
color: #333333;
text-anchor: end;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
.textlabel{
font-family: Arial;
font-size:13px;
color: #333333;
text-anchor: middle;
}
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
// Set the dimensions of the canvas / graph
var margin = {top: 20, right: 0, bottom: 60, left: 60},
width = 475;
height = 350;
padding = 100;
// Adds the svg canvas
var svg = d3.select("body")
.append("svg:svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("viewBox", "0 0 " + width + " " + height);
// Parse the date / time
var parseDate = d3.time.format("%m/%d/%y").parse;
var formatTax = d3.format(",.2f");
// Set the ranges
var x = d3.time.scale()
.range([0, width - margin.right - margin.left], .1)
.nice();
var y = d3.scale.linear()
.range([height - margin.top - margin.bottom, 20])
.nice();
// Define the axes
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(5);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(function(d) {return "$" + d + "B"});
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.Date); })
.y(function(d) { return y(d["Tax Collections"]); });
// Get the data
d3.csv("Yearly Tax Collections.csv", function(error, data) {
data.forEach(function(d) {
d.Date = parseDate(d.Date);
d["Tax Collections"] = formatTax(+d["Tax Collections"]/1000000000);
});
var g = svg.selectAll("g").data(data).enter().append("svg:g")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.Date; }));
y.domain([0, d3.max(data, function(d) { return Math.ceil (d["Tax Collections"]); })
]);
// Add the valueline path and mouseover
svg.append("path")
.attr("class", "line")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.attr("d", valueline(data))
.attr("id", "myPath")
.on("mousemove", mMove)
.append("title");
function mMove(){
var m = d3.mouse(this);
d3.select("#myPath")
.select("title")
.filter(function(d, i)
.attr({
'x':function(d,i) {
return x(d.Date);
},
'y':function(d,i) {
return y(d["Tax Collections"]);
}
})
.text(function(d,i){
return "$" + d["Tax Collections"] + "B";
})
}
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(" + margin.left + "," + (height - margin.bottom) + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(yAxis);
// Y-axis labels
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate ("+ (padding/4) + "," +(height/2)+") rotate(-90)")
.text("Tax Revenue")
.style("font-family", "Arial");
// X-axis labels
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate("+ (width/2) + "," +(height-(padding/4)) + ")")
.text("Fiscal Year")
.style("font-family", "Arial");
//source
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate("+ (width/4.5) + "," +(height/1) + ")")
.text("Source: DC OCFO")
.style("font-family", "Arial")
//title for the chart
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("color", "#333333")
.attr("transform", "translate("+ (width/3) + "," +(height/30) + ")")
.text("DC Total Tax Revenues by Fiscal Year")
.style("font-family", "Arial");
svg.append("text")
.attr("text-anchor", "left")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate("+ (width/20) + "," +(height/12) + ")")
.text("2000 to 2015")
.style("font-family", "Arial")
//line labels
svg.append('g')
.classed('labels-group', true)
.selectAll('text')
.data(data)
.enter()
.append('text')
.filter(function(d, i) { return i === 0||i === (data.length - 1) })
.classed('label',true)
.classed('label',true)
.attr({
'x':function(d,i) {
return x(d.Date);
},
'y':function(d,i) {
return y(d["Tax Collections"]);
}
})
.text(function(d,i){
return "$" + d["Tax Collections"] + "B";
})
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
});
</script>
</body>
Thank you in avance!
Hi I'm trying to get the mouseover function work for my line chart so I can hover over the line chart and see the values of each point. I tried using the mouse function but it didn't work. How can I do this? I also included a picture of the line chart
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Unemployment by Ward Bar Chart</title>
<style type="text/css">
.axis text{
font-family: Arial;
font-size: 13px;
color: #333333;
text-anchor: end;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
.textlabel{
font-family: Arial;
font-size:13px;
color: #333333;
text-anchor: middle;
}
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
// Set the dimensions of the canvas / graph
var margin = {top: 20, right: 0, bottom: 60, left: 60},
width = 475;
height = 350;
padding = 100;
// Adds the svg canvas
var svg = d3.select("body")
.append("svg:svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("viewBox", "0 0 " + width + " " + height);
// Parse the date / time
var parseDate = d3.time.format("%m/%d/%y").parse;
var formatTax = d3.format(",.2f");
// Set the ranges
var x = d3.time.scale()
.range([0, width - margin.right - margin.left], .1)
.nice();
var y = d3.scale.linear()
.range([height - margin.top - margin.bottom, 20])
.nice();
// Define the axes
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(5);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(function(d) {return "$" + d + "B"});
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.Date); })
.y(function(d) { return y(d["Tax Collections"]); });
// Get the data
d3.csv("Yearly Tax Collections.csv", function(error, data) {
data.forEach(function(d) {
d.Date = parseDate(d.Date);
d["Tax Collections"] = formatTax(+d["Tax Collections"]/1000000000);
});
var g = svg.selectAll("g").data(data).enter().append("svg:g")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.Date; }));
y.domain([0, d3.max(data, function(d) { return Math.ceil (d["Tax Collections"]); })
]);
// Add the valueline path and mouseover
svg.append("path")
.attr("class", "line")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.attr("d", valueline(data))
.append("title");
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(" + margin.left + "," + (height - margin.bottom) + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(yAxis);
// Y-axis labels
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate ("+ (padding/4) + "," +(height/2)+") rotate(-90)")
.text("Tax Revenue")
.style("font-family", "Arial");
// X-axis labels
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("color", "#333333")
. attr("transform", "translate("+ (width/2) + "," +(height-(padding/4)) + ")")
.text("Fiscal Year")
.style("font-family", "Arial");
//source
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate("+ (width/4.5) + "," +(height/1) + ")")
.text("Source: DC OCFO")
.style("font-family", "Arial")
//title for the chart
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("color", "#333333")
.attr("transform", "translate("+ (width/3) + "," +(height/30) + ")")
.text("DC Total Tax Revenues by Fiscal Year")
.style("font-family", "Arial");
svg.append("text")
.attr("text-anchor", "left")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate("+ (width/20) + "," +(height/12) + ")")
.text("2000 to 2015")
.style("font-family", "Arial")
//line labels
svg.append('g')
.classed('labels-group', true)
.selectAll('text')
.data(data)
.enter()
.append('text')
.filter(function(d, i) { return i === 0||i === (data.length - 1) })
.classed('label',true)
.classed('label',true)
.attr({
'x':function(d,i) {
return x(d.Date);
},
'y':function(d,i) {
return y(d["Tax Collections"]);
}
})
.text(function(d,i){
return "$" + d["Tax Collections"] + "B";
})
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
});
</script>
</body>
Thank you in advance!
While rendering your line labels, you just want to add an event listener for mouseover that shows and hides it. So it appears everything here is good to go except for showing and hiding your labels, which again you should do on mouseover/mouseout.
Here's an example of what I mean that I recently worked on:
g.append('svg:circle')
.attr('cx', function(){ return x(j.timestamp._d); })
.attr('cy', function(){ return y(j.value); })
.attr('r', 4)
.attr('stroke', ML.colors.array[i])
.attr('stroke-width', 2)
.attr('fill', '#ffffff')
.attr('class', 'circle-markers')
.attr('data-index', k)
.on('mouseover', function(){
$(this).attr('fill', ML.colors.array[i]);
}).on('mouseout', function(){
$(this).attr('fill', '#ffffff');
});
In this example I have a line chart with circles drawn at each point. The circles initially have a white center with a stroke but on mouseover the center fills in the same color as the stroke. Then of course on mouseout this reverses.
Hope this helps.
I made this bar chart but the only problem I'm facing is having it display below the title i.e below 2014. Right now it starts right next to 2014. How do I do this? I posted two pictures of the charts. One in tableau and the one I made using d3.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Housing Tenure of DC Residents</title>
<style type="text/css">
.axis text{
font-family: Arial;
font-size: 13px;
color: #333333;
text-anchor: end;
}
.axis path {
fill:none;
stroke:#333333 ;
stroke-width: 1.5px;
shape-rendering: crispEdges
font-family: Arial;
}
.bar{
stroke: none;
fill: #037FAA;
}
.axis .label{
font-family: Arial;
font-size:13px;
color: #333333;
text-anchor: middle;
}
.textlabel{
font-family: Arial;
font-size:13px;
color: #333333;
text-anchor: left;
}
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var outerWidth = 475;
var outerHeight = 350;
var margin = { left: 75, top: 20, right: 0, bottom: 60 };
var padding = 100;
var barPadding = 0.2;
var barPaddingOuter = 0.1;
var xColumn = "Percentage";
var yColumn = "LabelD3";
var xAxisLabelOffset = 75;
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)
.attr("viewBox", "0 0 " + outerWidth + " " + outerHeight);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var xAxisG = g.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + innerHeight + ")")
var yAxisG = g.append("g")
.attr("class", "y axis");
var xScale = d3.scale.linear()
.range([0, innerWidth - margin.right - margin.left], .1);
var yScale = d3.scale.ordinal()
.rangeRoundBands([innerHeight , 0], barPadding, barPaddingOuter);
var xAxis = d3.svg.axis().scale(xScale).orient("bottom")
.ticks(7)
.tickFormat(function(d) {return d + "%"});
var yAxis = d3.svg.axis().scale(yScale).orient("left");
function render(data){
xScale.domain([0, d3.max(data, function (d){ return d[xColumn]; })]);
yScale.domain( data.map( function (d){ return d[yColumn]; }));
xAxisG.call(xAxis);
yAxisG.call(yAxis);
var bars = g.selectAll("rect").data(data);
bars.enter().append("rect")
.attr("height", yScale.rangeBand());
bars
.attr("x", 0)
.attr("class", "bar")
.attr("y", function (d){ return yScale(d[yColumn]); })
.attr("width", function (d){ return xScale(d[xColumn]); });
// horizontal bar labels
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.selectAll(".textlabel")
.data(data)
.enter()
.append("text")
.attr("class", "textlabel")
.style("font-family", "Arial")
.attr("x", function(d){ return xScale(parseFloat(d["Percentage"])) ; })
.attr("y", function(d){ return yScale(d["LabelD3"]) + yScale.rangeBand()/2; })
.text(function(d){ return (d["Percentage"] + "%"); });
// X-axis labels
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate("+ (outerWidth/2) + "," +(outerHeight-(padding/4)) + ")")
.text("% of Households")
.style("font-family", "Arial");
//title for the chart
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("color", "#333333")
.attr("transform", "translate("+ (outerWidth/3.78) + "," +(outerHeight/30) + ")")
.text("Housing Tenure of DC Residents")
.style("font-family", "Arial");
//source
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate("+ (outerWidth/3.2) + "," +(outerHeight/1) + ")")
.text("Source: US Census ACS 5-year 2010-2014")
.style("font-family", "Arial")
svg.append("text")
.attr("text-anchor", "left")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate("+ (outerWidth/28) + "," +(outerHeight/12) + ")")
.text("2014")
.style("font-family", "Arial")
bars.exit().remove();
}
function type(d){
d.population = +d.population;
return d;
}
d3.csv("Housing.csv", type, render);
</script>
</body>
</html>
Thank you in advance!
This is the CSV:
LabelD3 Percentage
Own Home 41.6
Rent Home 58.4