Display Bar Chart below title in D3 - javascript

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

Related

I want create a graph with a button

I want show and hide a graph with the same button in d3.js.
I use d3.js to create this graph. I don't know if I have use a addlistener o something like that.
The d3.js code is as follows:
<style>
#wrapper
{
min-width:960px;
margin-left:auto;
margin-right:auto;
}
#top
{
width: 100%;
height: 40px;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.dot {
stroke: #000;
}
div.tooltip {
position: absolute;
text-align: center;
width: 60px;
height: 28px;
padding: 2px;
font: 12px sans-serif;
background: lightsteelblue;
border: 0px;
border-radius: 8px;
/* pointer-events: none; This line needs to be removed */
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 1300 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var div = d3.select("body")
.append("div") // declare the tooltip div
.attr("class", "tooltip") // apply the 'tooltip' class
.style("opacity", 0);
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("/projects/chart/data", function (error, data) {
if (error)
throw error;
data.forEach(function (d) {
d.sepalLength = +d.sepalLength;
d.sepalWidth = +d.sepalWidth;
});
x.domain(d3.extent(data, function (d) {
return d.sepalWidth;
})).nice();
y.domain(d3.extent(data, function (d) {
return d.sepalLength;
})).nice();
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("class", "label")
.attr("x", width)
.attr("y", -6)
.style("text-anchor", "end")
.text("Sepal Width (cm)");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("class", "label")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Sepal Length (cm)")
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function (d) {
return x(d.sepalWidth);
})
.attr("cy", function (d) {
return y(d.sepalLength);
})
.style("fill", function (d) {
return color(d.species);
})
.on("mouseover", function (d) {
div.transition()
.duration(500)
.style("opacity", 0);
div.transition()
.duration(200)
.style("opacity", .9);
div.html(
'<a href= "http://homestead.app/process/'+d.sepalWidth+'">' + // The first <a> tag
d.sepalWidth +
"</a>" + // closing </a> tag
"<br/>" + d.sepalLength)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
});
var legend = svg.selectAll(".legend")
.data(color.domain())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d, i) {
return "translate(0," + i * 20 + ")";
});
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function (d) {
return d;
});
});
</script>
I want to use the same button if it's possible.
Quick example of what could work :
HTML :
<button onclick='toggleGraph()'> </button>
JavaScript :
var showGraph = true;
function toggleGraph(){
var graph = d3.select('#graph'); //i recommend giving the graph an ID
if(showGraph){ //check bool
graph.style('visibility', 'hidden'); //hide graph
showGraph = false; //toggle bool
} else {
graph.style('visibility', 'visible'); //show graph
showGraph = true; //toggle bool
}
}

Mouseover functionality in d3 line chart

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!

Code to add mouseover functionality to line chart

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.

Selecting a section of data from CSV in d3.js

I created a bar chart by creating a new csv which was part of a bigger dataset. I want to now use the data from the original data set to plot my bar graph by selecting only two columns (Ward and Unemploymet) and one months data. How do I do this?
The code is below:
<!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;
}
.axis path{
fill:none;
stroke:#333333 ;
stroke-width: 1.5px;
shape-rendering: crispEdges
font-family: Arial;
}
.bar{
stroke: none;
fill: #012C3B;
}
.textlabel{
font-family: Arial;
font-size:13px;
color: #333333;
text-anchor: middle;
}
</style>
</head>
<body>
<script type="text/javascript" src="d3/d3.js"></script>
<script>
var margin = {top:20, right:0, bottom:60, left:60},
width = 475;
height = 350;
padding = 100;
var svg = d3.select("body")
.append("svg")
.attr("width", "30%")
.attr("height", "70%")
.attr("viewBox", "0 0 " + width + " " + height);
var yScale = d3.scale.linear()
.range([height - margin.top - margin.bottom, 0]);
var xScale = d3.scale.ordinal()
.rangeRoundBands([0, width - margin.right - margin.left], .1);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.tickFormat(function(d) {return d + "%"})
d3.csv("Unemployment.csv", function(error, data)
{
//map function goes through every element, then returns a number for Unemployment
data = data.map(function(d){
d["Unemployment"] = +d["Unemployment"];
return d;
});
//yscale's domain is from zero to the maximum "Unemployment"
yScale.domain([0, d3.max(data, function(d){ return d["Unemployment"]; })]);
//xscale is unique values in Ward (Ward, since they are all different)
xScale.domain(data.map(function(d){ return d["Ward"]; }));
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.selectAll(".bar")
.data(data)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d){ return xScale(d["Ward"]); })
.attr("y", function(d){ return yScale(d["Unemployment"]); })
.attr("height", function(d){ return height - margin.top - margin.bottom - yScale(d["Unemployment"]); })
.attr("width", function(d){ return xScale.rangeBand(); })
.style("font-family", "Arial");
//adding y axis to the chart
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(yAxis)
.style("color", "#333333")
.style("font-family", "Arial");
//adding x axis to the bottom of chart
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(" + margin.left + "," + (height - margin.bottom) + ")")
.call(xAxis)
.style("color", "#333333")
.style("font-family", "Arial");
//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")
.style("font-size", "15px")
.attr("x", function(d){ return xScale(d["Ward"]) + (xScale.rangeBand()/2); })
.attr("y", function(d){ return yScale(d["Unemployment"]) - 3 ; })
.text(function(d){ return (d["Unemployment"] + "%"); });
// 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("Unemployment")
.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("Ward")
.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.78) + "," +(height/30) + ")")
.text("Unemployment by Ward")
.style("font-family", "Arial");
//source
svg.append("text")
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("color", "#333333")
.attr("transform", "translate("+ (width/3.2) + "," +(height/1) + ")")
.text("Source:Bureau of Labor Statistics")
.style("font-family", "Arial")
})
</script>
</body>
</html
The CSV used for this is:
Ward Unemployment
1 4.5
2 4.3
3 4
4 5.7
5 7.9
6 5.2
7 11
8 14.2
I want to be able to change the code to select this part of the data set from a bigger csv which includes 56 rows and 6 columns. Can someone please help me with this? Thanks in advance.
You could filter the csv to create a subset of the data before passing it to d3.
At the top of your d3.csv call do something like
var newData = data.filter(filterCriteria);
And have a filterCriteria function that returns true or false based on what you want to show:
function filterCriteria(d) {
return d.month === targetMonth;
}
Where targetMonth equals the month you want to show.
Then pass newData to d3.

d3.js automatic data update - updateData

I made a simple bar chart using D3.js. The data for the chart is coming from a csv file. I would like for the chart to be updated every 2.5 seconds showing the new data. Right now, after updating the csv file the X and Y axis will update but the bars and mouseover tooltip shows the old values. I have looked at many different examples. Here are a few I have referenced. Anyone know what is going on?
http://mbostock.github.io/d3/tutorial/bar-2.html
http://www.d3noob.org/search?q=update
d3 update data and update graph
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Bar Chart</title>
<style type="text/css">
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
div.tooltip {
position: absolute;
text-align: left;
width: auto;
height: auto;
padding: 2px;
font-family: sans-serif;
font-size: 14px;
background: white;
border: 2;
border-radius: 5px;
pointer-events: none;
}
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 45},
width = 1000 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickPadding(5);
//var data = [{"label":"Boone","values":0.8},{"label":"Story","values":0.2},{"label":"Polk","values":0.4}]
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("position", "absolute")
.style("opacity", 0);
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.csv("data.csv", function(error, data) {
data.forEach(function(d) {
d.label = d.label;
d.values = +d.values;
});
x.domain(data.map(function(d) { return d.label; }));
y.domain([0, d3.max(data, function(d) { return d.values; })]);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-0)")
.attr("x", -10)
.attr("y", -16)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Values");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.on("mouseover", function(d) {
div.transition()
.duration(100)
.style("opacity", 1)
.style("left", (d3.event.pageX)+ "px")
.style("top", (d3.event.pageY) + "px");
div.html("<p>Label: " + d.label+ "<br>Value: " + d.values);
d3.select("#tooltip").classed("hidden", false);
})
.attr("class", "bar")
.attr("x", function(d) { return x(d.label); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.values); })
.attr("height", function(d) { return height - y(d.values); });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("class", "label")
.attr("x", width)
.attr("y", 30)
.style("text-anchor", "end")
.text("Label");
});
var inter = setInterval(function() {
updateData();
},2500);
function updateData() {
d3.csv("data.csv", function(error, data) {
data.forEach(function(d) {
d.label = d.label;
d.values = +d.values;
});
x.domain(data.map(function(d) { return d.label; }));
y.domain([0, d3.max(data, function(d) { return d.values; })]);
var svg = d3.select("body")
var vis = svg.transition();
vis.select(".x.axis")
.duration(750)
.call(xAxis)
vis.select(".y.axis")
.duration(750)
.call(yAxis)
vis.select(".rect")
.duration(750)
.attr(".x", function(d) { return x(d.label); })
.attr(".y", function(d) { return y(d.values); })
});
}
</script>
</body>
</html>

Categories