Second y axis on D3 column chart - javascript

I have a chart created with the code below. I want to add a second y axis positioned to the right which matches the same y scale. The reason I want the y axis on the right also is because of the limit line I have set at 16.5, the chart just doesn’t look right without the 2nd y axis.
<script>
var w = 800;
var h = 550;
var margin = {
top: 58,
bottom: 100,
left: 80,
right: 40
};
var width = w - margin.left - margin.right;
var height = h - margin.top - margin.bottom;
var threshold = 16.5;
var x = d3.scale.ordinal()
.domain(data.map(function(entry){
return entry.key;
}))
.rangeBands([0, width],.2);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d){
return d.value;
})])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var yGridLines = d3.svg.axis()
.scale(y)
.tickSize(-width, 0, 0)
.tickFormat("")
.orient("left");
var svg = d3.select("body").append("svg")
.attr("id", "chart")
.attr("width", w)
.attr("height", h);
var chart = svg.append("g")
.classed("display", true)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
function plot(params){
this.append("g")
.call(yGridLines)
.classed("gridline", true)
.attr("transform", "translate(0,0)")
this.selectAll(".bar")
.data(params.data)
.enter()
.append("rect")
.classed("bar", true)
.attr("x", function (d,i){
return x(d.key);
})
.attr("y", function(d,i){
return y(d.value);
})
.attr("height", function(d,i){
return height - y(d.value);
})
.attr("width", function(d){
return x.rangeBand();
});
this.selectAll(".bar-label")
.data(params.data)
.enter()
.append("text")
.classed("bar-label", true)
.attr("x", function(d,i){
return x(d.key) + (x.rangeBand()/2)
})
.attr("dx", 0)
.attr("y", function(d,i){
return y(d.value);
})
.attr("dy", -6)
.text(function(d){
return d.value;
})
this.append("g")
.classed("x axis", true)
.attr("transform", "translate(" + 0 + "," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", -8)
.attr("dy" ,8)
.attr("transform", "translate(0,0) rotate(-45)");
this.append("g")
.classed("y axis", true)
.attr("transform", "translate(0,0)")
.call(yAxis);
this.select(".y.axis")
.append("text")
.attr("x", 0)
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(-50," + height/2 + ") rotate(-90)")
.text("Downtime [Hrs]");
this.select(".x.axis")
.append("text")
.attr("x", 0)
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + width/2 + ",80)")
.text("[Stations]");
// title
this.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("text-decoration", "underline")
.text("Over Mould");
// limit line
this.append("line")
.attr("x1", 0)
.attr("y1", y(threshold))
.attr("x2", width)
.attr("y2", y(threshold))
.attr("stroke-width", 2)
.attr("stroke", "yellow");
}
d3.json('data.json', function(data) {
plot.call(chart, {data: data});
});
</script>
Data is coming from an external JSON file.
[
{
"key": "ING_SW_CB",
"value": "7"
},
{
"key": "SB_SW_CB",
"value": "15"
},
{
"key": "NG3_SW_CB",
"value": "3"
},
{
"key": "Mould_Close",
"value": "8"
},
{
"key": "Leak_Test",
"value": "9"
},
{
"key": "ML_Load",
"value": "2"
},
{
"key": "Pre_Heat",
"value": "1"
},
{
"key": "Dispense",
"value": "5"
},
{
"key": "A310",
"value": "6"
},
{
"key": "Gelation",
"value": "5"
},
{
"key": "Platen",
"value": "7"
},
{
"key": "Mainline_Unload",
"value": "8"
},
{
"key": "De_mould",
"value": "5"
},
{
"key": "Clean_Up",
"value": "4"
},
{
"key": "Soda_Blast",
"value": "5"
},
{
"key": "RMI",
"value": "15"
},
{
"key": "Miscellaneous",
"value": "5"
}
]
My idea was to create yAxis2 and call it later in the function that plots the chart.
var yAxis2 = d3.svg.axis()
.scale(y)
.orient("right");
this.append("g")
.classed("y axis", true)
.attr("transform", "translate(width,0)")
.call(yAxis2);
When I do this it just draws it in the same place as the first yAxis, when I adjust the transform/ translate it just gets drawn at random positions on the chart, I'm trying to line it up like the left yAxis only positioned on the right. Thanks to all for your input.

Syntax error:
.attr("transform", "translate(width,0)")
To:
.attr("transform", "translate(" + width + ",0)")
plnkr

Related

Show values on top of line graph

I'm trying to display values on the top of line graph using d3 js. How can I append values to the path of the line graph?
And How can I display month-year as X-axis ticks like May'18, June'19?
I tried using the below code, but the values are not displaying.
lineSvg.selectAll("path")
.data(data)
.enter().append("text")
.attr("class", "line")
.attr("text-anchor", "middle")
.attr("x", function(d) { return 10; })
.attr("y", function(d) { return yscale(d.value) - 5; })
.text(function(d) { return d.value; });
Here is my complete code:
var data = [{
"date": "2018-1",
"value": 40.13,
"status": 1
}, {
"date": "2018-2",
"value": 45.88,
"status": 1
}, {
"date": "2018-3",
"value": 50.89,
"status": 1
}, {
"date": "2018-4",
"value": 55.87,
"status": 1
}, {
"date": "2018-5",
"value": 88.54,
"status": 1
}, {
"date": "2018-6",
"value": 74.41,
"status": 1
}, {
"date": "2018-7",
"value": 98.56,
"status": 1
}, {
"date": "2018-8",
"value": 81.05,
"status": 1
}, {
"date": "2018-9",
"value": 58.13,
"status": 1
}, {
"date": "2018-10",
"value": 95.86,
"status": 1
}, {
"date": "2018-11",
"value": 78.13,
"status": 1
}, {
"date": "2018-12",
"value": 98.86,
"status": 1
}, {
"date": "2019-1",
"value": 105.86,
"status": 0
}, {
"date": "2019-2",
"value": 110.86,
"status": 0
}];
/* Monday 2012 */
var data1 = data
var dateformat = "%Y-%m"
drawTimeSeriesGraph(data1, dateformat);
/*
Tooltip from: http://bl.ocks.org/d3noob/6eb506b129f585ce5c8a
line graph from here: http://www.d3noob.org/2012/12/starting-with-basic-d3-line-graph.html
*/
function drawTimeSeriesGraph(data, dateformat) {
//Set bounds for red dots
var lbound = 0.045,
ubound = 0.075;
// Set the dimensions of the canvas / graph
var margin = {
top: 50,
right: 150,
bottom: 50,
left: 50
},
width = 900 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format(dateformat).parse,
formatDate = d3.time.format(dateformat),
bisectDate = d3.bisector(function(d) {
return d.date;
}).left;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(10);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(10);
// Define the line
var valueline = d3.svg.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.value);
}).interpolate("linear");
var full_date = new Date();
var day = full_date.getDay(); //returns 0 - 6
var month = full_date.getMonth() + 1; //returns 0 - 11
var year = full_date.getFullYear(); //returns 4 digit year ex: 2000
var my = year + "-" + month;
//alert(my);
// Adds the svg canvas
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var lineSvg = svg.append("g");
var focus = svg.append("g")
.style("display", "none");
// Get the data
data.forEach(function(d) {
d.date = parseDate(d.date);
d.value = +d.value;
});
// 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 d.value;
})]);
//Use below if instead you want to define the y limits:
//y.domain([0, 0.11]);
// Add the valueline path.
var lineGraph2 = lineSvg.append("path")
.attr("class", "line")
.attr("d", valueline(data.filter(function(d) {
return d.status > 0;
})))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
var lineGraph1 = lineSvg.append("path")
.attr("class", "line")
.attr("d", valueline(data.slice(-3)))
.attr("stroke", "red")
.attr("stroke-width", 2)
.attr("fill", "none");
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
// append the x line
focus.append("line")
.attr("class", "x")
.style("stroke", "blue")
.style("stroke-dasharray", "3,3")
.style("opacity", 0.5)
.attr("y1", 0)
.attr("y2", height);
// append the y line
focus.append("line")
.attr("class", "y")
.style("stroke", "blue")
.style("stroke-dasharray", "3,3")
.style("opacity", 0.5)
.attr("x1", width)
.attr("x2", width);
// append the circle at the intersection
focus.append("circle")
.attr("class", "y")
.style("fill", "none")
.style("stroke", "blue")
.attr("r", 4);
// place the value at the intersection
focus.append("text")
.attr("class", "y1")
.style("stroke", "white")
.style("stroke-width", "3.5px")
.style("opacity", 0.8)
.attr("dx", 8)
.attr("dy", "-.3em");
focus.append("text")
.attr("class", "y2")
.attr("dx", 8)
.attr("dy", "-.3em");
// place the date at the intersection
focus.append("text")
.attr("class", "y3")
.style("stroke", "white")
.style("stroke-width", "3.5px")
.style("opacity", 0.8)
.attr("dx", 8)
.attr("dy", "1em");
focus.append("text")
.attr("class", "y4")
.attr("dx", 8)
.attr("dy", "1em");
// append the rectangle to capture mouse
svg.append("rect")
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all")
.on("mouseover", function() {
focus.style("display", null);
})
.on("mouseout", function() {
focus.style("display", "none");
})
.on("mousemove", mousemove);
function mousemove() {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(data, x0, 1),
d0 = data[i - 1],
d1 = data[i],
d = x0 - d0.date > d1.date - x0 ? d1 : d0;
focus.select("circle.y")
.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")");
focus.select("text.y1")
.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")")
.text(d.value.toFixed(2));
focus.select("text.y2")
.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")")
.text(d.value.toFixed(2));
focus.select("text.y3")
.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")")
.text(formatDate(d.date));
focus.select("text.y4")
.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")")
.text(formatDate(d.date));
focus.select(".x")
.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")")
.attr("y2", height - y(d.value));
focus.select(".y")
.attr("transform", "translate(" + width * -1 + "," + y(d.value) + ")")
.attr("x2", width + width);
};
svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("text-decoration", "underline")
};
I'm trying to get line graph like this:
For the axis you have to set the tickFormat.
xAxis.tickFormat(d3.time.format("%b'%y"));
or if you want full month name
xAxis.tickFormat(d3.time.format("%B'%y"));
For the text just add them like you do with circles or rects
svg.selectAll(".val").data(data)
.enter()
.append('text')
.attr("x", d => x(d.date))
.attr("y", d => y(d.value))
.attr("dy", "-0.5em")
.attr("text-anchor", "middle")
.text(d => d.value);

D3 V5 Bar chart

Okay I am trying to make a bar chart. This is the Javascript I have.
var data = [
{
"date": "1459468800000", // 1 April 2016
"values": [{
"name": "US",
"value": 72580613,
"domainname": "com"
}, {
"name": "US",
"value": 161645,
"domainname": "nl"
}]
}, {
"date": "1467331200000", // 1 Juli 2016
"values": [{
"name": "US",
"value": 73129243,
"domainname": "com"
}, {
"name": "US",
"value": 166152,
"domainname": "nl"
}]
}
]
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var tooltip = d3.select("body").append("div").attr("class");
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
y = d3.scaleLinear().rangeRound([height, 0]);
var colours = d3.scaleOrdinal()
.range(["#6F257F", "#CA0D59"]);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(data.map(function(d) { return d.values.domainname; }));
y.domain([0, d3.max(data, function(d) { return d.values.value; })]);
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y).ticks(25).tickFormat(function(d) { return parseInt(d / 1000) + "K"; }).tickSizeInner([-width]))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.attr("fill", "#5D6971")
.text("Aantal domeinen");
g.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("x", function(d) { return x(d.values.domainname); })
.attr("y", function(d) { return y(d.values.value); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.values.value); })
.attr("fill", function(d) { return colours(d.values.domainname); })
As you can see I have the data in an array. In the data I have 2 different dates.
For now I only want to show the first date in the bar chart but both domains (com & nl as bars (In the future I will ad more domains to the dates). (If you are interested : The idea is to make a dropdown on the page so the user can select another date and the bars will update).
What I have now is that I can see the axises on my screen so that is working good. But I got this error :
So D3 is expecting a number but it doesn't get one on the Y axis and the heigth as I understand the error...
How can I fix that it is displaying the first date with the domains correct?
The access to the values was incorrect instead of d.values.domainname or d.values.value you have to use d.values[i].domainname and d.values[i].value.
Here you can see your example running.
var data = [
{
"date": "1459468800000", // 1 April 2016
"values": [{
"name": "US",
"value": 72580613,
"domainname": "com"
}, {
"name": "US",
"value": 161645,
"domainname": "nl"
}]
}, {
"date": "1467331200000", // 1 Juli 2016
"values": [{
"name": "US",
"value": 73129243,
"domainname": "com"
}, {
"name": "US",
"value": 166152,
"domainname": "nl"
}]
}
]
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var tooltip = d3.select("body").append("div").attr("class");
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
y = d3.scaleLinear().rangeRound([height, 0]);
var colours = d3.scaleOrdinal()
.range(["#6F257F", "#CA0D59"]);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(data.map(function(d, i) { return d.values[i].domainname; }));
y.domain([0, d3.max(data, function(d, i) { return d.values[i].value; })]);
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y).ticks(25).tickFormat(function(d) { return parseInt(d / 1000) + "K"; }).tickSizeInner([-width]))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.attr("fill", "#5D6971")
.text("Aantal domeinen");
g.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("x", function(d, i) { return x(d.values[i].domainname); })
.attr("y", function(d, i) { return y(d.values[i].value); })
.attr("width", x.bandwidth())
.attr("height", function(d, i) {return height - y(d.values[i].value)})
.attr("fill", function(d, i) { return colours(d.values[i].domainname); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="400" height="400"></svg>
As a note the column nl looks especially small because the values are too different.

How to transition between updated data of bar chart, in d3?

I'm trying to get an understanding of transitions in bar charts using D3. What I'm doing now is updating the chart between two different data sets. I have a transition included but it's starting from the the bottom of the axis rather than transitioning between the two. My goal is to have it transition between the two and later change the colors. I'm using this helpful example for understanding updated data (my snippet is not much different). Thank you for taking a look.
var bothData = [
{
"year": "2014",
"product": "Books & DVDs",
"purchase": "0.5"
},
{
"year": "2002",
"product": "Books & DVDs",
"purchase": "10"
},
{
"year": "2014",
"product": "Beer & Wine",
"purchase": "7"
},
{
"year": "2002",
"product": "Beer & Wine",
"purchase": "3"
},
{
"year": "2014",
"product": "Food",
"purchase": "12"
},
{
"year": "2002",
"product": "Food",
"purchase": "12"
},
{
"year": "2014",
"product": "Home Supplies",
"purchase": "7"
},
{
"year": "2002",
"product": "Home Supplies",
"purchase": "6"
}
];
var data2002 = [];
var data2014 = [];
for(var i = 0; i < bothData.length; i++){
if(bothData[i]["year"] === "2002"){
data2002.push(bothData[i]);
}else{
data2014.push(bothData[i]);
}
}
function change(value){
if(value === '2002'){
update(data2002);
}else if(value === '2014'){
update(data2014);
}
}
function update(data){
xChart.domain(data.map(function(d){ return d.product; }) );
yChart.domain( [0, d3.max(data, function(d){ return + d.purchase; })] );
var barWidth = width / data.length;
var bars = chart.selectAll(".bar")
.remove()
.exit()
.data(data, function(d){ return d.purchase; })
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d, i){ return i * barWidth + 1 })
.attr("y",500)
.attr("height",0)
.attr("width", barWidth - 5)
.each(function(d){
if(d.year === "2014"){
d3.select(this)
.style('fill','#ea5454');
}else{
d3.select(this)
.style('fill','#4e97c4');
};
});
bars.transition()
.duration(600)
.ease(d3.easeLinear)
.attr('y', function(d){ return yChart(d.purchase); })
.attr('height', function(d){ return height - yChart(d.purchase); });
chart.select('.y').call(yAxis);
chart.select('.xAxis')
.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)";
});
}
var margin = {top: 20, right: 20, bottom: 95, left: 50};
var width = 400;
var height = 500;
var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var xChart = d3.scaleBand()
.range([0, width]);
var yChart = d3.scaleLinear()
.range([height, 0]);
var xAxis = d3.axisBottom(xChart);
var yAxis = d3.axisLeft(yChart);
chart.append("g")
.attr("class", "y axis")
.call(yAxis)
chart.append("g")
.attr("class", "xAxis")
.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)";
});
chart.append("text")
.attr("transform", "translate(-35," + (height+margin.bottom)/2 + ") rotate(-90)")
.text("Purchases");
chart.append("text")
.attr("transform", "translate(" + (width/2) + "," + (height + margin.bottom - 5) + ")")
.text("Products");
update(data2002);
You have the right idea...you want to achieve object constancy as described here by Mike Bostock. The key for your constancy should be the "product" from your data (not "purchase").
In your update function, define bars like this:
var bars = chart.selectAll(".bar")
.data(data, function(d){ return d.product; })
then separate the .enter, .exit and .transition functions:
bars.exit()
.remove()
bars.enter()
....
bars.transition()
You have some strange stuff going on in your .enter function - like setting bar height to zero. So I modified your .enter and .transition functions like this:
bars.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d, i){return i * barWidth + 1 })
.attr("y",function(d){ return yChart(d.purchase); })
.attr("height",function(d){ return height - yChart(d.purchase); })
.attr("width", barWidth - 5)
.attr('fill', function(d){
if(d.year === "2014"){
return'#ea5454'
}else{
return'#4e97c4'
}
})
bars.transition()
.duration(600)
.ease(d3.easeLinear)
.attr('y', function(d){ return yChart(d.purchase); })
.attr('height', function(d){ return height - yChart(d.purchase); })
.style('fill', function(d){
if(d.year === "2014"){
return '#ea5454'
} else {
return '#4e97c4'
}
})
Here is a working jsfiddle: https://jsfiddle.net/genestd/asoLph2w/
Note the buttons on top to achieve the transition.

D3.js line chart with dates on x axes

I'm working on this line chart with d3.js .
I have a problem formatting the dates and as much I change the parseDate field, there is no way I can find to get for example "15 June".
If I change .tickformat in the x axis on %d I will just have "01 Oct" and not the exact date.
Here is the JS fiddle
http://jsfiddle.net/w0d4t1n5/
<script async src="//jsfiddle.net/w0d4t1n5/embed/"></script>
Thanks for your help!
If I understand, you want every datapoint's date displayed on the x axis, instead of just a time division.
For that, you need to create an ordinal scale and call that in the X axis:
fiddle is here:
http://jsfiddle.net/z94uzc0L/1/
var margin = {
top: 30,
right: 100,
bottom: 30,
left: 50
},
width = 365 - margin.left - margin.right,
height = 280 - margin.top - margin.bottom,
padding = 1;
var parseDate = d3.time.format("%d-%b-%y").parse;
// Set the ranges
var x = d3.time.scale()
.range([10, width - 15]);
//ordinal scale
var x2 = d3.scale.ordinal().rangePoints([0, width ], .25)
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis().scale(x2)
.orient("bottom")
.tickFormat(d3.time.format("%b %d"))
.ticks(4)
.tickPadding(2);
var yAxis = d3.svg.axis().scale(y)
.orient("left");
var valueline = d3.svg.line()
.interpolate("basis")
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.trump);
});
var valueline2 = d3.svg.line()
.interpolate("basis")
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.clinton);
});
//florida
var chart1 = d3.select("#florida")
.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 + ")");
//needed for the grid
function make_y_axis() {
return d3.svg.axis()
.scale(y)
.orient("left")
}
data1 = [{
"date": "15-Jun-16",
"trump": 43.4,
"clinton": 44
}, {
"date": "15-Jul-16",
"trump": 43.4,
"clinton": 44
}, {
"date": "15-Aug-16",
"trump": 42,
"clinton": 45.6
}, {
"date": "15-Sep-16",
"trump": 45.1,
"clinton": 44.4
}, {
"date": "06-Oct-16",
"trump": 43.3,
"clinton": 46.2
}, {
"date": "10-Oct-16",
"trump": 49.3,
"clinton": 49.2
}];
var color = d3.scale.ordinal().range(["#004ecc", "#cc0000"]);
//d3.csv("data.csv", function(error, data) {
data1.forEach(function(d) {
d.date = parseDate(d.date);
d.trump = +d.trump;
d.clinton = +d.clinton;
});
// Scale the range of the data
x.domain(d3.extent(data1, function(d) {
return d.date;
}));
y.domain([36, 50]);
//update ordinal scale domain
x2.domain(data1.map(function(d) { return d.date; }));
//add the grid
chart1.append("g")
.attr("class", "grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat("")
)
chart1.append("path")
.attr("class", "line")
.attr("stroke", "red")
.attr("d", valueline(data1));
chart1.append("path")
.attr("class", "line2")
.attr("d", valueline2(data1));
// Add the X Axis
chart1.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
chart1.append("g")
.attr("class", "y axis")
.call(yAxis);
chart1.append("text")
.attr("transform", "translate(" + (width + 3) + "," + y(data1[0].clinton) + ")")
.attr("x", ".1em")
.attr("y", "-40")
.attr("text-anchor", "start")
.style("fill", "red")
.style("font-size", "15")
.style("font-weight", "bold")
.text("Clinton 46.2%");
chart1.append("text")
.attr("transform", "translate(" + (width + 3) + "," + y(data1[0].trump) + ")")
.attr("x", ".1em")
.attr("y", "10")
.attr("text-anchor", "start")
.style("fill", "steelblue")
.style("font-size", "15")
.style("font-weight", "bold")
.text("Trump 43.3%");
//plus 1: animation
var curtain = chart1.append('rect')
.attr('x', -1 * width)
.attr('y', -1 * height)
.attr('height', height)
.attr('width', width)
.attr('class', 'curtain')
.attr('transform', 'rotate(180)')
.style('fill', '#ffffff')
/* Optionally add a guideline */
var guideline = chart1.append('line')
.attr('stroke', '#333')
.attr('stroke-width', 0.4)
.attr('class', 'guide')
.attr('x1', 1)
.attr('y1', 1)
.attr('x2', 1)
.attr('y2', height)
var t = chart1.transition()
.delay(120)
.duration(500)
.ease('linear')
.each('end', function() {
d3.select('line.guide')
.transition()
.style('opacity', 0)
.remove()
});
t.select('rect.curtain')
.attr('width', 0);
t.select('line.guide')
.attr('transform', 'translate(' + width + ', 0)')
d3.select("#show_guideline").on("change", function(e) {
guideline.attr('stroke-width', this.checked ? 1 : 0);
curtain.attr("opacity", this.checked ? 0.75 : 1);
});

D3.js: Moving circles along with line in a 2D graph when zoomed

I am currently trying to plot a time series data in d3.js. I have rendered a line and plotted circles for each data point (In the future circles would be used to annotate specific data points). I am trying to zoom all the components using the "zoom" behaviour in d3.js. But I am unable to drag and zoom the circle along the line.
How can i move the circles along with line. Following is the jsfiddle for the code:
https://jsfiddle.net/adityap16/4sts8nfs/2/
Code:
var data = [{
"mytime": "2015-12-01T23:10:00.000Z",
"value": 64
}, {
"mytime": "2015-12-01T23:15:00.000Z",
"value": 67
}, {
"mytime": "2015-12-01T23:20:00.000Z",
"value": 70
}, {
"mytime": "2015-12-01T23:25:00.000Z",
"value": 64
}, {
"mytime": "2015-12-01T23:30:00.000Z",
"value": 72
}, {
"mytime": "2015-12-01T23:35:00.000Z",
"value": 75
}, {
"mytime": "2015-12-01T23:40:00.000Z",
"value": 71
}, {
"mytime": "2015-12-01T23:45:00.000Z",
"value": 80
}, {
"mytime": "2015-12-01T23:50:00.000Z",
"value": 83
}, {
"mytime": "2015-12-01T23:55:00.000Z",
"value": 86
}, {
"mytime": "2015-12-02T00:00:00.000Z",
"value": 80
}, {
"mytime": "2015-12-02T00:05:00.000Z",
"value": 85
}];
var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ").parse;
data.forEach(function(d) {
d.mytime = parseDate(d.mytime);
});
//var margin = { top: 30, right: 30, bottom: 40, left:50 },
var margin = {
top: 30,
right: 30,
bottom: 40,
left: 50
},
height = 200,
width = 900;
var color = "green";
var xaxis_param = "mytime";
var yaxis_param = "value";
var params1 = {
margin: margin,
height: height,
width: width,
color: color,
xaxis_param: xaxis_param,
yaxis_param: yaxis_param
};
draw_graph(data, params1);
function draw_graph(data, params) {
var make_x_axis = function() {
return d3.svg.axis()
.scale(x_scale)
.orient("bottom")
.ticks(5);
};
var make_y_axis = function() {
return d3.svg.axis()
.scale(y_scale)
.orient("left")
.ticks(5);
};
//Get the margin
var xaxis_param = params.xaxis_param;
var yaxis_param = params.yaxis_param;
var color_code = params.color;
var margin = params.margin;
var height = params.height - margin.top - margin.bottom,
width = params.width - margin.left - margin.right;
var x_extent = d3.extent(data, function(d) {
return d[xaxis_param]
});
var y_extent = d3.extent(data, function(d) {
return d[yaxis_param]
});
var x_scale = d3.time.scale()
.domain(x_extent)
.range([0, width]);
var y_scale = d3.scale.linear()
.domain([0, y_extent[1]])
.range([height, 0]);
var zoom = d3.behavior.zoom()
.x(x_scale)
.y(y_scale)
.on("zoom", zoomed);
//Line
var line = d3.svg.line()
.defined(function(d) {
return d[yaxis_param];
})
.x(function(d) {
return x_scale(d[xaxis_param]);
})
.y(function(d) {
return y_scale(d[yaxis_param]);
});
var lineRef = d3.svg.line()
.x(function(d) {
return x_scale(d[xaxis_param]);
})
.y(function(d) {
return y_scale(20);
});
var myChart = d3.select('body').append('svg')
.attr('id', 'graph')
.style('background', '#E7E0CB')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')')
.call(zoom);
myChart.append("svg:rect")
.attr("width", width)
.attr("height", height)
.attr("class", "plot");
var legend = myChart.append("g")
.attr("class", "legend")
.attr("transform", "translate(" + 5 + "," + (height - 25) + ")")
legend.append("rect")
.style("fill", color_code)
.attr("width", 20)
.attr("height", 20);
legend.append("text")
.text(yaxis_param)
.attr("x", 25)
.attr("y", 12);
var vAxis = d3.svg.axis()
.scale(y_scale)
.orient('left')
.ticks(5)
var hAxis = d3.svg.axis()
.scale(x_scale)
.orient('bottom')
.ticks(5);
var majorAxis = d3.svg.axis()
.scale(x_scale)
.orient('bottom')
.ticks(d3.time.day, 1)
.tickSize(-height)
.outerTickSize(0);
myChart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(hAxis);
myChart.append("g")
.attr("class", "x axis major")
.attr("transform", "translate(0," + height + ")")
.call(majorAxis);
myChart.append("g")
.attr("class", "y axis")
.call(vAxis);
var circlePoint = myChart.selectAll('circle')
.data(data)
.enter()
.append("circle");
var circleAttributes = circlePoint
.attr("cx", function (d) { return x_scale(d[xaxis_param]); })
.attr("cy", function (d) { return y_scale(d[yaxis_param]); })
.attr("r", 3)
.style("fill", "none")
.style("stroke", "red");
var clip = myChart.append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height);
var chartBody = myChart.append("g")
.attr("clip-path", "url(#clip)");
chartBody.append("svg:path")
.datum(data)
.attr('class', 'line')
.attr("d", line)
.attr('stroke', color_code)
.attr('stroke-width', 1)
.attr('fill', 'none');
chartBody
.append('svg:path')
.datum(data)
.attr('class', 'line1')
.attr("d", lineRef)
.attr('stroke', 'blue')
.attr('stroke-width', 1)
.style("stroke-dasharray", ("3, 3"))
.attr('fill', 'none');
function zoomed() {
myChart.select(".x.axis").call(hAxis);
myChart.select(".y.axis").call(vAxis);
myChart.select(".x.axis.major").call(majorAxis);
myChart.select(".line")
.attr("class", "line")
.attr("d", line);
myChart.select(".line1")
.attr("class", "line1")
.attr("d", lineRef);
}
}
You just need to update the circles' positions in your zoomed() handler function:
circlePoint
.attr("cx", function (d) { return x_scale(d[xaxis_param]); })
.attr("cy", function (d) { return y_scale(d[yaxis_param]); });
Because D3's zoom behavior will have taken care of updating the scales, they can easily be used for calculating the new positions.
Have a look at this snippet for a full example:
var data = [{
"mytime": "2015-12-01T23:10:00.000Z",
"value": 64
}, {
"mytime": "2015-12-01T23:15:00.000Z",
"value": 67
}, {
"mytime": "2015-12-01T23:20:00.000Z",
"value": 70
}, {
"mytime": "2015-12-01T23:25:00.000Z",
"value": 64
}, {
"mytime": "2015-12-01T23:30:00.000Z",
"value": 72
}, {
"mytime": "2015-12-01T23:35:00.000Z",
"value": 75
}, {
"mytime": "2015-12-01T23:40:00.000Z",
"value": 71
}, {
"mytime": "2015-12-01T23:45:00.000Z",
"value": 80
}, {
"mytime": "2015-12-01T23:50:00.000Z",
"value": 83
}, {
"mytime": "2015-12-01T23:55:00.000Z",
"value": 86
}, {
"mytime": "2015-12-02T00:00:00.000Z",
"value": 80
}, {
"mytime": "2015-12-02T00:05:00.000Z",
"value": 85
}];
var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ").parse;
data.forEach(function(d) {
d.mytime = parseDate(d.mytime);
});
//var margin = { top: 30, right: 30, bottom: 40, left:50 },
var margin = {
top: 30,
right: 30,
bottom: 40,
left: 50
},
height = 200,
width = 900;
var color = "green";
var xaxis_param = "mytime";
var yaxis_param = "value";
var params1 = {
margin: margin,
height: height,
width: width,
color: color,
xaxis_param: xaxis_param,
yaxis_param: yaxis_param
};
draw_graph(data, params1);
function draw_graph(data, params) {
var make_x_axis = function() {
return d3.svg.axis()
.scale(x_scale)
.orient("bottom")
.ticks(5);
};
var make_y_axis = function() {
return d3.svg.axis()
.scale(y_scale)
.orient("left")
.ticks(5);
};
//Get the margin
var xaxis_param = params.xaxis_param;
var yaxis_param = params.yaxis_param;
var color_code = params.color;
var margin = params.margin;
var height = params.height - margin.top - margin.bottom,
width = params.width - margin.left - margin.right;
var x_extent = d3.extent(data, function(d) {
return d[xaxis_param]
});
var y_extent = d3.extent(data, function(d) {
return d[yaxis_param]
});
var x_scale = d3.time.scale()
.domain(x_extent)
.range([0, width]);
var y_scale = d3.scale.linear()
.domain([0, y_extent[1]])
.range([height, 0]);
var zoom = d3.behavior.zoom()
.x(x_scale)
.y(y_scale)
.on("zoom", zoomed);
//Line
var line = d3.svg.line()
.defined(function(d) {
return d[yaxis_param];
})
.x(function(d) {
return x_scale(d[xaxis_param]);
})
.y(function(d) {
return y_scale(d[yaxis_param]);
});
var lineRef = d3.svg.line()
.x(function(d) {
return x_scale(d[xaxis_param]);
})
.y(function(d) {
return y_scale(20);
});
var myChart = d3.select('body').append('svg')
.attr('id', 'graph')
.style('background', '#E7E0CB')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')')
.call(zoom);
myChart.append("svg:rect")
.attr("width", width)
.attr("height", height)
.attr("class", "plot");
var legend = myChart.append("g")
.attr("class", "legend")
.attr("transform", "translate(" + 5 + "," + (height - 25) + ")")
legend.append("rect")
.style("fill", color_code)
.attr("width", 20)
.attr("height", 20);
legend.append("text")
.text(yaxis_param)
.attr("x", 25)
.attr("y", 12);
var vAxis = d3.svg.axis()
.scale(y_scale)
.orient('left')
.ticks(5)
var hAxis = d3.svg.axis()
.scale(x_scale)
.orient('bottom')
.ticks(5);
var majorAxis = d3.svg.axis()
.scale(x_scale)
.orient('bottom')
.ticks(d3.time.day, 1)
.tickSize(-height)
.outerTickSize(0);
myChart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(hAxis);
myChart.append("g")
.attr("class", "x axis major")
.attr("transform", "translate(0," + height + ")")
.call(majorAxis);
myChart.append("g")
.attr("class", "y axis")
.call(vAxis);
var circlePoint = myChart.selectAll('circle')
.data(data)
.enter()
.append("circle");
var circleAttributes = circlePoint
.attr("cx", function (d) { return x_scale(d[xaxis_param]); })
.attr("cy", function (d) { return y_scale(d[yaxis_param]); })
.attr("r", 3)
.style("fill", "none")
.style("stroke", "red");
var clip = myChart.append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height);
var chartBody = myChart.append("g")
.attr("clip-path", "url(#clip)");
chartBody.append("svg:path")
.datum(data)
.attr('class', 'line')
.attr("d", line)
.attr('stroke', color_code)
.attr('stroke-width', 1)
.attr('fill', 'none');
chartBody
.append('svg:path')
.datum(data)
.attr('class', 'line1')
.attr("d", lineRef)
.attr('stroke', 'blue')
.attr('stroke-width', 1)
.style("stroke-dasharray", ("3, 3"))
.attr('fill', 'none');
function zoomed() {
myChart.select(".x.axis").call(hAxis);
myChart.select(".y.axis").call(vAxis);
myChart.select(".x.axis.major").call(majorAxis);
myChart.select(".line")
.attr("class", "line")
.attr("d", line);
myChart.select(".line1")
.attr("class", "line1")
.attr("d", lineRef);
circlePoint
.attr("cx", function (d) { return x_scale(d[xaxis_param]); })
.attr("cy", function (d) { return y_scale(d[yaxis_param]); });
}
}
svg {
font: 10px sans-serif;
}
.plot {
fill: rgba(250, 250, 255, 0.6);
}
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Categories

Resources