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!
Related
I would like to add a tooltip to the line chart, where each data point displays a text box upon hover, as follows:
-----------------|
x-coordinate: ## |
y-coordinate: ## |
-----------------|
The working snippet for the working graph is posted below. But I will comment out the tooltip block to plot the chart.
Thanks.
var margin = {top: 50, right: 50, bottom: 50, left: 50}
, width = window.innerWidth - margin.left - margin.right
, height = window.innerHeight - margin.top - margin.bottom;
//labels
var labels = ['Mon','Tue','Thur','Frid'];
var yvals = [12,11,0,18];
// X scale
var xScale = d3.scalePoint()
.domain(labels) // input
.range([0, width-1]); // output
// Y scale
var yScale = d3.scaleLinear()
.domain([0, 20])
.range([height,0]);
var line = d3.line()
.x(function(d, i) { return xScale(labels[i]); })
.y(function(d) { return yScale(d.y); })
.curve(d3.curveMonotoneX)
var dataset = d3.range(yvals.length).map(function(d,i) { return {"y": yvals[i]} })
//Tooltip
//var tip = d3.select('body')
//.append('div')
//.attr('class', 'tip')
//.html('number:'+ function(d,i) return {data[data.i]})
// .style('border', '1px solid steelblue')
// .style('padding', '5px')
//.style('position', 'absolute')
// .style('display', 'none')
//.on('mouseover', function(d, i) {
// tip.transition().duration(0);
// })
// .on('mouseout', function(d, i) {
// tip.style('display', 'none');
// });
// SVGs
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 + ")");
svg.append("rect")
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "white");
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// x axis call
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
//.call(d3.axisBottom(xScale));
.call(d3.axisBottom(xScale));
// y axis call
svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(yScale));
svg.append("path")
.datum(dataset)
.attr("class", "line")
.attr("d", line);
// 12. Appends a circle for each datapoint
svg.selectAll(".dot")
.data(dataset)
.enter().append("circle") // Uses the enter().append() method
.attr("class", "dot") // Assign a class for styling
.attr("cx", function(d, i) { return xScale(labels[i]) })
.attr("cy", function(d,i) { return yScale(yvals[i]) })
.attr("r", 3);
//.on('mouseover', function(d, i) {
// tip.transition().duration(0);
// })
svg.append("text")
.attr("class", "title")
.attr("x", width/2)
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.text("Testing");
.line {
fill: none;
stroke: orange;
stroke-width: 1;
}
.dot {
fill: brown;
stroke: #fff;
}
<!DOCTYPE html>
<meta charset="utf-8">
<style type="text/css">
</style>
<body>
</body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
</script>
I have just made a few changes to the mousemove event.
var margin = {
top: 50,
right: 50,
bottom: 50,
left: 50
},
width = window.innerWidth - margin.left - margin.right,
height = window.innerHeight - margin.top - margin.bottom;
//labels
var labels = ['Mon', 'Tue', 'Thur', 'Frid'];
var yvals = [12, 11, 0, 18];
// X scale
var xScale = d3.scalePoint()
.domain(labels) // input
.range([0, width - 1]); // output
// Y scale
var yScale = d3.scaleLinear()
.domain([0, 20])
.range([height, 0]);
var line = d3.line()
.x(function(d, i) {
return xScale(labels[i]);
})
.y(function(d) {
return yScale(d.y);
})
.curve(d3.curveMonotoneX)
var dataset = d3.range(yvals.length).map(function(d, i) {
return {
"y": yvals[i]
}
})
var tip = d3.select('body').append("div")
.attr("class", "tip");
// SVGs
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 + ")");
svg.append("rect")
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "white");
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// x axis call
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
//.call(d3.axisBottom(xScale));
.call(d3.axisBottom(xScale));
// y axis call
svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(yScale));
svg.append("path")
.datum(dataset)
.attr("class", "line")
.attr("d", line);
// 12. Appends a circle for each datapoint
svg.selectAll(".dot")
.data(dataset)
.enter().append("circle") // Uses the enter().append() method
.attr("class", "dot") // Assign a class for styling
.attr("cx", function(d, i) {
return xScale(labels[i])
})
.attr("cy", function(d, i) {
return yScale(yvals[i])
})
.attr("r", 3)
.on("mouseover", function() {
tip.style("display", null);
})
.on("mouseout", function() {
tip.style("display", "none");
})
.on("mousemove", function(d) {
return tip
.style("left", d3.event.pageX + "px")
.style("top", d3.event.pageY + 10 + "px")
.style("visibility", "visible")
.html(function() {
return '<div style="border:1px solid #ccc;">' +
'<p style="font-weight:bold;">' + d.y + '</p>' +
'</div>';
})
})
svg.append("text")
.attr("class", "title")
.attr("x", width / 2)
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.text("Testing");
.line {
fill: none;
stroke: orange;
stroke-width: 1;
}
.dot {
fill: brown;
stroke: #fff;
}
.tip {
position: absolute;
border: 1px solid steelblue;
visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.0.0/d3.min.js"></script>
Here is the working jsFiddle
Hope it helps :)
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 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.
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
I'm using on d3.js, and it's working fine.But i'm not figuring out to insert zoom. I'm using a snippet to inser the zoom inside the chart.
this is my code:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.dot {
stroke: #35353a;
}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var margin = {top: 40, right: 50, bottom: 60, left: 70},
width = 1060 - margin.left - margin.right,
height = 700 - 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 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.tsv("data/test.tsv", function(error, data) {
if (error) throw error;
data.forEach(function(d) {
d.y = +d.y;
d.x = +d.x;
});
x.domain(d3.extent(data, function(d) { return d.x; })).nice();
y.domain(d3.extent(data, function(d) { return d.y; })).nice();
svg.append("rect")
.style('fill', 'transparent')
.attr("width", width)
.attr("height", height);
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("1° Principal Component");
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("2° Principal Component")
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) { return x(d.x); })
.attr("cy", function(d) { return y(d.y); })
.style("fill", function(d) { return color(d.cluster); });
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>
if I insert the code to zoom, i'm not able to see the graph again:
var zoom = d3.behavior.zoom()
.scaleExtent([1, 10])
.on("zoom", zoomed);
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.right + ")")
.call(zoom);-> add zoom to svg
function zoomed() {
container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
what's wrong?
little snippet of tsv:
x y cluster
-1.0403321821456555 -0.9975352942962847 1 Cluster
-1.0404728255519613 -1.0021499065423058 1 Cluster
-1.0405312135780753 -1.0036348433263207 1 Cluster
-1.0405417259454817 -0.9883123582794969 1 Cluster
-1.0406344016908704 -0.9988259809896288 1 Cluster
-1.0406850822323188 -1.004030268612692 1 Cluster
-1.0406958447337742 -1.0065636473623911 1 Cluster
-1.0408667295862442 -1.0046081788513885 1 Cluster
-1.0408845367165218 -0.995137367062602 1 Cluster
-1.040932294864444 -0.991519347648691 1 Cluster
-1.040976952803462 -0.9833995692226501 1 Cluster
-1.0409896369345166 -0.9951495809699621 1 Cluster
-1.0410051379794218 -0.99448305469843 1 Cluster
-1.0410265061033306 -0.9951333768928067 1 Cluster
-1.0410330574179099 -0.9949308462686461 1 Cluster
-1.0410357249485886 -1.0053243527321372 1 Cluster
-1.0410491702402065 -1.006726904241483 1 Cluster
-1.041049812593761 -0.9865506278675225 1 Cluster
-1.0410667719605575 -0.9911033214658317 1 Cluster
-1.0411116340142055 -0.9735253204825465 1 Cluster
thanks in advance.
I am playing blind here as I don't have a running code:
function zoomed() {
container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
This should have been:
function zoomed() {
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
Explanation: I see the code does not have a container; the translate should be on the g group appended to svg.