Related
This question is actually a continuation of the question from here. I have made some changes to my fiddle and code since then but I am still facing the same problem. Link to my fiddle and code can be found here.
I am using a for loop to plot the lines as I want the chart to be dynamic which means the number of lines is drawn according to the number of arrays in the data array. In this case, there are 2 arrays in my data array as shown below.
var data = [[{x: 0, y: 0}, {x: 10, y: 10}, {x: 20, y: 20}, {x: 30, y: 30}, {x: 40, y: 40}],
[{x: 0, y: 0}, {x: 10, y: 200}, {x: 20, y: 300}, {x: 30, y: 400}, {x: 40, y: 500}]];
From my fiddle, the blue line will be toggled on and off when I click on both 'Y-Axis 1' and 'Y-Axis 2'. However, I want the red line to be toggled on and off when I click on Y-Axis 2. This is happening because I am assigning the same id to both lines in this piece of code.
//************* Plotting of graph ***************
var colors = ["blue", "red"];
//plot of chart
for (var i = 0; i < 2; i++){
var lineFunction = d3.line()
.x(function(d) {return x(d.x); })
.y(function(d) {return yScale[i](d.y); })
.curve(d3.curveLinear);
//plot lines
var paths = g.append("path")
.attr("class", "path1")
.attr("id", "blueLine")
.attr("d", lineFunction(data[i]))
.attr("stroke", colors[i])
.attr("stroke-width", 2)
.attr("fill", "none")
.attr("clip-path", "url(#clip)")
//plot a circle at each data point
g.selectAll(".dot")
.data(data[i])
.enter().append("circle")
.attr("cx", function(d) { return x(d.x)} )
.attr("cy", function(d) { return yScale[i](d.y); } )
.attr("r", 3)
.attr("class", "blackDot")
.attr("clip-path", "url(#clip)")
.on("mouseover", mouseover )
.on("mouseleave", mouseleave )
}
Is there a better way to plot the lines so that I can assign a specific id to each line being plotted and toggle the lines according to the legend? I have tried using forEach() but can't seem to get it to work. Any help is greatly appreciated!
First of all: you should not use a loop (for, while, forEach etc...) to append elements in a D3 code. That's not idiomatic, and you'll end up bending over backwards to fix things, like this very question will demonstrate.
The simplest fix without refactoring the code for a more idiomatic one, which will take a lot of work, is using the indices for setting the lines' IDs...
var paths = g.append("path")
.attr("class", "path1")
.attr("id", "blueLine" + i)
... and then, in the click listener, using this cumbersome and awkward window property, which is the elements' IDs:
.on("click", function(d, i) {
var active = window["blueLine" + i].active ? false : true,
newOpacity = active ? 0 : 1;
d3.select("#blueLine" + i).style("opacity", newOpacity);
window["blueLine" + i].active = active;
});
Here is your code with those changes:
var xValueArray = [0, 10, 20, 30, 40];
var arr = [
[0, 10, 20, 30, 40],
[0, 200, 300, 400, 500]
];
//data array is obtained after structuring arr array
var data = [
[{
x: 0,
y: 0
}, {
x: 10,
y: 10
}, {
x: 20,
y: 20
}, {
x: 30,
y: 30
}, {
x: 40,
y: 40
}],
[{
x: 0,
y: 0
}, {
x: 10,
y: 200
}, {
x: 20,
y: 300
}, {
x: 30,
y: 400
}, {
x: 40,
y: 500
}]
];
const margin = {
left: 20,
right: 20,
top: 20,
bottom: 80
};
const svg = d3.select('svg');
svg.selectAll("*").remove();
const width = 200 - margin.left - margin.right;
const height = 200 - margin.top - margin.bottom;
//const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);
const g = svg.append('g').attr('transform', `translate(${80},${margin.top})`);
//************* Axes and Gridlines ***************
const xAxisG = g.append('g');
const yAxisG = g.append('g');
xAxisG.append('text')
.attr('class', 'axis-label')
.attr('x', width / 3)
.attr('y', -10)
.style('fill', 'black')
.text(function(d) {
return "X Axis";
});
yAxisG.append('text')
.attr('class', 'axis-label')
.attr('id', 'primaryYLabel')
.attr('x', -height / 2)
.attr('y', -15)
.attr('transform', `rotate(-90)`)
.style('text-anchor', 'middle')
.style('fill', 'black')
.text(function(d) {
return "Y Axis 1";
});
// interpolator for X axis -- inner plot region
var x = d3.scaleLinear()
.domain([0, d3.max(xValueArray)])
.range([0, width])
.nice();
var yScale = new Array();
for (var i = 0; i < 2; i++) {
// interpolator for Y axis -- inner plot region
var y = d3.scaleLinear()
.domain([0, d3.max(arr[i])])
.range([0, height])
.nice();
yScale.push(y);
}
const xAxis = d3.axisTop()
.scale(x)
.ticks(5)
.tickPadding(2)
.tickSize(-height)
const yAxis = d3.axisLeft()
.scale(yScale[0])
.ticks(5)
.tickPadding(2)
.tickSize(-width);
yAxisArray = new Array();
yAxisArray.push(yAxis);
for (var i = 1; i < 2; i++) {
var yAxisSecondary = d3.axisLeft()
.scale(yScale[i])
.ticks(5)
yAxisArray.push(yAxisSecondary);
}
svg.append("g")
.attr("class", "x axis")
.attr("transform", `translate(80,${height-80})`)
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(80,20)")
.call(yAxis);
//************* Mouseover ***************
var tooltip = d3.select("body")
.append("div")
.style("opacity", 0)
.attr("class", "tooltip")
.style("background-color", "white")
.style("border", "solid")
.style("border-width", "1px")
.style("border-radius", "5px")
.style("padding", "10px")
.style("position", "absolute")
// A function that change this tooltip when the user hover a point.
// Its opacity is set to 1: we can now see it. Plus it set the text and position of tooltip depending on the datapoint (d)
var mouseover = function(d) {
tooltip
.html("x: " + d.x + "<br/>" + "y: " + d.y)
.style("opacity", 1)
.style("left", (d3.mouse(this)[0] + 90) + "px")
.style("top", (d3.mouse(this)[1]) + "px")
}
// A function that change this tooltip when the leaves a point: just need to set opacity to 0 again
var mouseleave = function(d) {
tooltip
.transition()
.duration(200)
.style("opacity", 0)
}
//************* Plotting of graph ***************
var colors = ["blue", "red"];
//plot of chart
for (var i = 0; i < 2; i++) {
var lineFunction = d3.line()
.x(function(d) {
return x(d.x);
})
.y(function(d) {
return yScale[i](d.y);
})
.curve(d3.curveLinear);
//plot lines
var paths = g.append("path")
.attr("class", "path1")
.attr("id", "blueLine" + i)
.attr("d", lineFunction(data[i]))
.attr("stroke", colors[i])
.attr("stroke-width", 2)
.attr("fill", "none")
.attr("clip-path", "url(#clip)")
//plot a circle at each data point
g.selectAll(".dot")
.data(data[i])
.enter().append("circle")
.attr("cx", function(d) {
return x(d.x)
})
.attr("cy", function(d) {
return yScale[i](d.y);
})
.attr("r", 3)
.attr("class", "blackDot")
.attr("clip-path", "url(#clip)")
.on("mouseover", mouseover)
.on("mouseleave", mouseleave)
}
var translation = 50;
var textTranslation = 0;
var yLabelArray = ["Y Axis 1", "Y Axis 2"];
//loop starts from 1 as primary y axis is already plotted
for (var i = 1; i < 2; i++) {
svg.append("g")
.attr("transform", "translate(" + translation + "," + 20 + ")")
.call(yAxisArray[i]);
yAxisG.append('text')
.attr('x', -height / 2)
.attr('y', -60)
.attr('transform', `rotate(-90)`)
.style('text-anchor', 'middle')
.style('fill', 'black')
.text(yLabelArray[i]);
translation -= 20;
textTranslation += 20;
}
//************* Legend ***************
var legend = svg.selectAll('.legend')
.data(data)
.enter()
.append('g')
.attr('class', 'legend');
legend.append('rect')
.attr('x', width - 5)
.attr('y', function(d, i) {
return (i * 20) + 120;
})
.attr('width', 18)
.attr('height', 4)
.attr("fill", function(d, i) {
return colors[i]
});
legend.append('text')
.attr('x', width - 10)
.attr('y', function(d, i) {
return (i * 20) + 120;
})
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d, i) {
return yLabelArray[i]
})
.on("click", function(d, i) {
//Determine if current line is visible
var active = window["blueLine" + i].active ? false : true,
newOpacity = active ? 0 : 1;
//Hide or show the elements
d3.select("#blueLine" + i).style("opacity", newOpacity);
//Update whether or not the elements are active
window["blueLine" + i].active = active;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<svg class="xy_chart"></svg>
I have implemented a zoom function for my chart, where one can zoom into a certain area of the chart by dragging the area and releasing it. My fiddle is accessible here.
The zoom function is working correctly for the blue line as both the blue line and the left axis is being updated. However, the right axis is not being updated while the red line is zoomed in. I have hardcoded a domain from 0 to 200 for the right axis so whenever I zoom in the domain goes from 0 to 200 instead of the correct zoomed in domain. What should be the code for the domain for the axis on the right so that it gets updated during the zoom? Any help is greatly appreciated!
var data = [ {x: 0, y: 0, y1: 0}, {x: 1, y: 30, y1: 100}, {x: 2, y: 40, y1: 200},
{x: 3, y: 60, y1: 300}, {x: 4, y: 70, y1: 400}, {x: 5, y: 90, y1: 500} ];
const margin = {
left: 20,
right: 20,
top: 20,
bottom: 80
};
const svg = d3.select('svg');
svg.selectAll("*").remove();
const width = 200 - margin.left - margin.right;
const height = 200 - margin.top - margin.bottom;
const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);
var x = d3.scaleLinear()
.domain([0, d3.max(data, function(d){ return d.x; })])
.range([0,width])
.nice();
var y = d3.scaleLinear()
.domain([0, d3.max(data, function(d){ return d.y; })])
.range([0,height])
.nice();
var y1 = d3.scaleLinear()
.domain([0, d3.max(data, function(d) { return d.y1; })])
.range([0, height])
.nice();
const xAxis = d3.axisTop()
.scale(x)
.ticks(5)
.tickPadding(3)
.tickSize(-height)
const yAxis = d3.axisLeft()
.scale(y)
.ticks(5)
.tickPadding(3)
.tickSize(-width);
const yAxis1 = d3.axisRight()
.scale(y1)
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(20,20)")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(20,20)")
.call(yAxis);
svg.append("g")
.attr("class", "y1 axis")
.attr("transform", "translate(185,20)")
.call(yAxis1);
var lineFunction = d3.line()
.x(function(d) {return x(d.x); })
.y(function(d) {return y(d.y); })
.curve(d3.curveLinear);
var lineFunctionOne = d3.line()
.x(function(d) {return x(d.x); })
.y(function(d) {return y1(d.y1); })
.curve(d3.curveLinear);
//defining and plotting the lines
var path = g.append("path")
.attr("class", "path1")
.attr("id", "blueLine")
.attr("d", lineFunction(data))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none")
.attr("clip-path", "url(#clip)");
var path1 = g.append("path")
.attr("class", "path2")
.attr("id", "redLine")
.attr("d", lineFunctionOne(data))
.attr("stroke", "red")
.attr("stroke-width", 2)
.attr("fill", "none")
.attr("clip-path", "url(#clip)");
//************* Zoom ***************
//add brushing
var brush = d3.brush().extent([[0, 0], [width, height]]).on("end", brushended),
idleTimeout,
idleDelay = 350;
g.append("g")
.attr("class", "brush")
.call(brush);
// Add a clipPath: everything out of this area won't be drawn when chart is zoomed in
var clip = svg.append("defs").append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("width", width)
.attr("height", height)
.attr("x", 0)
.attr("y", 0);
function brushended() {
var s = d3.event.selection;
//If no selection, re-initialize chart on double click. Otherwise, update x-axis and y-axis domain
if (!s) {
// This allows to wait a little bit
if (!idleTimeout) return idleTimeout = setTimeout(idled, 350);
x.domain(d3.extent(data, function (d) { return d.x; })).nice();
y.domain(d3.extent(data, function (d) { return d.y; })).nice();
y1.domain(d3.extent(data, function (d) { return d.y1; })).nice();
} else {
x.domain([s[0][0], s[1][0]].map(x.invert, x));
y.domain([s[0][1], s[1][1]].map(y.invert, y));
y1.domain([0, 200]); //hardcoded domain
//This removes the grey brush area as soon as the selection has been done
g.select(".brush").call(brush.move, null)
}
zoom();
}
function idled() {
idleTimeout = null;
}
function zoom() {
var t = svg.transition().duration(750);
svg.select(".x.axis").transition(t).call(xAxis);
svg.select(".y.axis").transition(t).call(yAxis);
svg.select(".y1.axis").transition(t).call(yAxis1);
svg.select(".path1").transition(t).attr("d", lineFunction(data));
svg.select(".path2").transition(t).attr("d", lineFunctionOne(data));
}
I'm puzzled by your question... all you need to do is the same thing you did just the line above it:
y1.domain([s[0][1], s[1][1]].map(y1.invert, y));
By the way, you don't need the thisArg in the map, it can be just:
y1.domain([s[0][1], s[1][1]].map(y1.invert));
Here is the updated code:
var data = [{
x: 0,
y: 0,
y1: 0
}, {
x: 1,
y: 30,
y1: 100
}, {
x: 2,
y: 40,
y1: 200
},
{
x: 3,
y: 60,
y1: 300
}, {
x: 4,
y: 70,
y1: 400
}, {
x: 5,
y: 90,
y1: 500
}
];
const margin = {
left: 20,
right: 20,
top: 20,
bottom: 80
};
const svg = d3.select('svg');
svg.selectAll("*").remove();
const width = 200 - margin.left - margin.right;
const height = 200 - margin.top - margin.bottom;
const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);
var x = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return d.x;
})])
.range([0, width])
.nice();
var y = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return d.y;
})])
.range([0, height])
.nice();
var y1 = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return d.y1;
})])
.range([0, height])
.nice();
const xAxis = d3.axisTop()
.scale(x)
.ticks(5)
.tickPadding(3)
.tickSize(-height)
const yAxis = d3.axisLeft()
.scale(y)
.ticks(5)
.tickPadding(3)
.tickSize(-width);
const yAxis1 = d3.axisRight()
.scale(y1)
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(20,20)")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(20,20)")
.call(yAxis);
svg.append("g")
.attr("class", "y1 axis")
.attr("transform", "translate(185,20)")
.call(yAxis1);
var lineFunction = d3.line()
.x(function(d) {
return x(d.x);
})
.y(function(d) {
return y(d.y);
})
.curve(d3.curveLinear);
var lineFunctionOne = d3.line()
.x(function(d) {
return x(d.x);
})
.y(function(d) {
return y1(d.y1);
})
.curve(d3.curveLinear);
//defining the lines
var path = g.append("path")
.attr("class", "path1")
.attr("id", "blueLine")
.attr("d", lineFunction(data))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none")
.attr("clip-path", "url(#clip)");
var path1 = g.append("path")
.attr("class", "path2")
.attr("id", "redLine")
.attr("d", lineFunctionOne(data))
.attr("stroke", "red")
.attr("stroke-width", 2)
.attr("fill", "none")
.attr("clip-path", "url(#clip)");
//************* Zoom ***************
//add brushing
var brush = d3.brush().extent([
[0, 0],
[width, height]
]).on("end", brushended),
idleTimeout,
idleDelay = 350;
g.append("g")
.attr("class", "brush")
.call(brush);
// Add a clipPath: everything out of this area won't be drawn when chart is zoomed in
var clip = svg.append("defs").append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("width", width)
.attr("height", height)
.attr("x", 0)
.attr("y", 0);
function brushended() {
var s = d3.event.selection;
//If no selection, re-initialize chart on double click. Otherwise, update x-axis and y-axis domain
if (!s) {
// This allows to wait a little bit
if (!idleTimeout) return idleTimeout = setTimeout(idled, 350);
x.domain(d3.extent(data, function(d) {
return d.x;
})).nice();
y.domain(d3.extent(data, function(d) {
return d.y;
})).nice();
y1.domain(d3.extent(data, function(d) {
return d.y1;
})).nice();
} else {
x.domain([s[0][0], s[1][0]].map(x.invert, x));
y.domain([s[0][1], s[1][1]].map(y.invert, y));
y1.domain([s[0][1], s[1][1]].map(y1.invert, y)); //hardcoded domain
//This removes the grey brush area as soon as the selection has been done
g.select(".brush").call(brush.move, null)
}
zoom();
}
function idled() {
idleTimeout = null;
}
function zoom() {
var t = svg.transition().duration(750);
svg.select(".x.axis").transition(t).call(xAxis);
svg.select(".y.axis").transition(t).call(yAxis);
svg.select(".y1.axis").transition(t).call(yAxis1);
svg.select(".path1").transition(t).attr("d", lineFunction(data));
svg.select(".path2").transition(t).attr("d", lineFunctionOne(data));
}
.xy_chart {
position: relative;
left: 50px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<svg class="xy_chart"></svg>
I have created the stacked bar chart by using d3.js.In that I would like to display a single bar with different colors to highlight the data for particular x axis value like below.
The script i have used to plot stacked chart is below:
// Set the dimensions of the canvas / graph
var svg = d3.select("#svgID"),
margin = {top: 80, right: 140, bottom: 100, left: 100},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var padding = -100;
//set the ranges
var x = d3.scaleBand()
.rangeRound([0, width])
.paddingInner(0.20)
.align(0.1);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
var z = d3.scaleOrdinal()
.range(["#008000", "#C00000", "#404040", "#4d4d4d"]);
var data = $("#svgID").data("values");
var keys = ["Pass", "Fail", "Average", "Worst"];
var legendKeysbar = ["Pass", "Fail", "Average", "Worst"];
var legendColorsbar = d3.scaleOrdinal()
.range(["#008000", "#C00000", "#404040", "#4d4d4d"]);
// Scale the range of the data
x.domain(data.map(function (d) {
return d.year;
}));
y.domain([0, d3.max(data, function (d) {
return d.total;
})]).nice();
z.domain(keys);
// add the Y gridlines
g.append("g").selectAll(".hline").data(y.ticks(10)).enter()
.append("svg:line")
.attr("x1", 0)
.attr("y1", function(d){ return y(d);})
.attr("x2", width)
.attr("y2", function(d){ return y(d);})
.style("stroke", "white")
.style("stroke-width", 1);
// append the rectangles for the bar chart
g.append("g")
.selectAll("g")
.data(d3.stack().keys(keys)(data))
.enter().append("g")
.attr("fill", function (d) {
return z(d.key);
})
.selectAll("rect")
.data(function (d) {
return d;
})
.enter().append("rect")
.attr("x", function (d) {
return x(d.data.year);
})
.attr("y", function (d) {
return y(d[1]);
})
.attr("height", function (d) {
return y(d[0]) - y(d[1]);
})
Can you help me to update colors for single bar? is that possible by d3.js
Create a second color scale, then in the method where you assign color, perform a check to determine which color scale to use, e.g.,:
var z2 = d3.scaleOrdinal().range(<your color array here>)
...
.attr("fill", function (d) {
return d.data.year === "Dec" ? z2(d.key) : z(d.key);
})
I have been searching for a while about how to handle the X axis in a stacked bar chart (since dataset is a little different from a single bar chart).
Basically, I have data for a 24hr period in 15 minute intervals. However, I only want to display the x-axis in 2hr ticks.
Existing Fiddle: [https://jsfiddle.net/lucksp/crwb4v5u/][1]
It currently prints all the intervals.
I have tried various scale options with time but something doesn't translate with the way I have this setup.
var xScale = d3.scale.ordinal()
.domain(dataset[0].map(function(d) {
return d.x;
}))
.rangeRoundBands([0, width - margin.left]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.tickSize(0)
.ticks(12)
.tickFormat(function(d) {
return d;
});
var rect = groups.selectAll('rect')
.data(function(d) {
return d;
})
.enter()
.append('rect')
.attr('class', function(d, i) {
return 'stacks ' + d.type;
})
.classed('stacks', true)
.attr('id', function(d, i) {
return d.type + '_' + i;
})
.attr('x', function(d) {
return xScale(d.x);
})
.attr('y', function(d) {
return yScale(d.y0 + d.y);
})
.attr('height', function(d) {
return yScale(d.y0) - yScale(d.y0 + d.y);
})
.attr('width', xScale.rangeBand());
[1]: https://jsfiddle.net/lucksp/crwb4v5u/
I know it's user error, but after looking at this for the last 2 days, I am resorting to asking this question now. Thanks!
You are currently trying to use .ticks which will only work if the scale you're using has an inbuilt ticks function. Your ordinal scale in this case does not. It will by default use all values in the domain.
To go around it, we can manually set the ticks using xAxis.tickValues(["custom tick values that match domain vals"]). Check the snippet below.
var data = [{"hour":"0:00","inProgress":3,"inQueue":0},{"hour":"0:15","inProgress":5,"inQueue":3},{"hour":"0:30","inProgress":1,"inQueue":1},{"hour":"0:45","inProgress":1,"inQueue":0},{"hour":"1:00","inProgress":2,"inQueue":0},{"hour":"1:15","inProgress":8,"inQueue":2},{"hour":"1:30","inProgress":5,"inQueue":3},{"hour":"1:45","inProgress":5,"inQueue":1},{"hour":"2:00","inProgress":6,"inQueue":0},{"hour":"2:15","inProgress":6,"inQueue":0},{"hour":"2:30","inProgress":7,"inQueue":0},{"hour":"2:45","inProgress":7,"inQueue":0},{"hour":"3:00","inProgress":8,"inQueue":0},{"hour":"3:15","inProgress":8,"inQueue":0},{"hour":"3:30","inProgress":9,"inQueue":1},{"hour":"3:45","inProgress":9,"inQueue":4},{"hour":"4:00","inProgress":10,"inQueue":6},{"hour":"4:15","inProgress":10,"inQueue":2},{"hour":"4:30","inProgress":10,"inQueue":1},{"hour":"4:45","inProgress":11,"inQueue":0},{"hour":"5:00","inProgress":11,"inQueue":0},{"hour":"5:15","inProgress":12,"inQueue":0},{"hour":"5:30","inProgress":12,"inQueue":0},{"hour":"5:45","inProgress":13,"inQueue":0},{"hour":"6:00","inProgress":13,"inQueue":0},{"hour":"6:15","inProgress":14,"inQueue":0},{"hour":"6:30","inProgress":14,"inQueue":0},{"hour":"6:45","inProgress":15,"inQueue":0},{"hour":"7:00","inProgress":15,"inQueue":3},{"hour":"7:15","inProgress":15,"inQueue":1},{"hour":"7:30","inProgress":16,"inQueue":0},{"hour":"7:45","inProgress":16,"inQueue":0},{"hour":"8:00","inProgress":17,"inQueue":2},{"hour":"8:15","inProgress":17,"inQueue":3},{"hour":"8:30","inProgress":18,"inQueue":1},{"hour":"8:45","inProgress":18,"inQueue":0},{"hour":"9:00","inProgress":19,"inQueue":0},{"hour":"9:15","inProgress":19,"inQueue":0},{"hour":"9:30","inProgress":20,"inQueue":0},{"hour":"9:45","inProgress":20,"inQueue":0},{"hour":"10:00","inProgress":20,"inQueue":0},{"hour":"10:15","inProgress":21,"inQueue":1},{"hour":"10:30","inProgress":21,"inQueue":4},{"hour":"10:45","inProgress":22,"inQueue":6},{"hour":"11:00","inProgress":22,"inQueue":2},{"hour":"11:15","inProgress":23,"inQueue":1},{"hour":"11:30","inProgress":23,"inQueue":0},{"hour":"11:45","inProgress":3,"inQueue":0},{"hour":"12:00","inProgress":5,"inQueue":0},{"hour":"12:15","inProgress":1,"inQueue":0},{"hour":"12:30","inProgress":1,"inQueue":0},{"hour":"12:45","inProgress":2,"inQueue":0},{"hour":"13:00","inProgress":8,"inQueue":0},{"hour":"13:15","inProgress":5,"inQueue":0},{"hour":"13:30","inProgress":5,"inQueue":0},{"hour":"13:45","inProgress":6,"inQueue":3},{"hour":"14:00","inProgress":6,"inQueue":1},{"hour":"14:15","inProgress":7,"inQueue":0},{"hour":"14:30","inProgress":7,"inQueue":0},{"hour":"14:45","inProgress":8,"inQueue":2},{"hour":"15:00","inProgress":8,"inQueue":3},{"hour":"15:15","inProgress":9,"inQueue":1},{"hour":"15:30","inProgress":9,"inQueue":0},{"hour":"15:45","inProgress":10,"inQueue":0},{"hour":"16:00","inProgress":10,"inQueue":0},{"hour":"16:15","inProgress":10,"inQueue":0},{"hour":"16:30","inProgress":11,"inQueue":0},{"hour":"16:45","inProgress":11,"inQueue":0},{"hour":"17:00","inProgress":12,"inQueue":1},{"hour":"17:15","inProgress":12,"inQueue":4},{"hour":"17:30","inProgress":13,"inQueue":6},{"hour":"17:45","inProgress":13,"inQueue":2},{"hour":"18:00","inProgress":14,"inQueue":1},{"hour":"18:15","inProgress":14,"inQueue":0},{"hour":"18:30","inProgress":15,"inQueue":0},{"hour":"18:45","inProgress":15,"inQueue":0},{"hour":"19:00","inProgress":15,"inQueue":0},{"hour":"19:15","inProgress":16,"inQueue":0},{"hour":"19:30","inProgress":16,"inQueue":0},{"hour":"19:45","inProgress":17,"inQueue":0},{"hour":"20:00","inProgress":17,"inQueue":0},{"hour":"20:15","inProgress":18,"inQueue":0},{"hour":"20:30","inProgress":18,"inQueue":3},{"hour":"20:45","inProgress":19,"inQueue":1},{"hour":"21:00","inProgress":19,"inQueue":0},{"hour":"21:15","inProgress":20,"inQueue":0},{"hour":"21:30","inProgress":20,"inQueue":2},{"hour":"21:45","inProgress":20,"inQueue":3},{"hour":"22:00","inProgress":21,"inQueue":1},{"hour":"22:15","inProgress":21,"inQueue":0},{"hour":"22:30","inProgress":22,"inQueue":0},{"hour":"22:45","inProgress":22,"inQueue":0},{"hour":"23:00","inProgress":23,"inQueue":0},{"hour":"23:15","inProgress":23,"inQueue":0},{"hour":"23:30","inProgress":1,"inQueue":0},{"hour":"23:45","inProgress":2,"inQueue":1}];
var margin = {top: 20, right: 50, bottom: 30, left: 20},
width = 500,
height = 300;
// Transpose the data into layers
var dataset = d3.layout.stack()(['inProgress', 'inQueue'].map(function(types) {
return data.map(function(d) {
return {
x: d.hour,
y: +d[types],
type: types
};
});
}));
var svg = d3.select('svg'),
margin = {top: 40, right: 10, bottom: 20, left: 10},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Set x, y and colors
var xScale = d3.scale.ordinal()
.domain(dataset[0].map(function(d) {
return d.x;
}))
.rangeRoundBands([0, width - margin.left]);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {
return d3.max(d, function(d) {
return d.y0 + d.y;
});
})])
.range([height, 0]);
var colors = ['#56a8f8', '#c34434'];
// Define and draw axes
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left')
.ticks(5)
.tickSize(0)
.tickFormat(function(d) {
return d;
});
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.tickSize(0)
.ticks(12) // this
.tickFormat(function(d) {
return d; // and this will not work with an ordinal scale
});
xAxis.tickValues(["0:00", "2:00", "4:00", "6:00", "8:00", "10:00", "12:00", "14:00", "16:00", "18:00", "20:00", "22:00"]);
svg.append('g')
.attr('class', 'y axis')
.call(yAxis);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
// Create groups for each series, rects for each segment
var groups = svg.selectAll('g.bar-stacks')
.data(dataset)
.enter().append('g')
.attr('class', function(d, i) {
return 'bar-stacks ' + d[i].type;
})
.classed('bar-stacks', true)
.style('fill', function(d, i) {
return colors[i];
});
var rect = groups.selectAll('rect')
.data(function(d) {
return d;
})
.enter()
.append('rect')
.attr('class', function(d, i) {
return 'stacks ' + d.type;
})
.classed('stacks', true)
.attr('id', function(d, i) {
return d.type + '_' + i;
})
.attr('x', function(d) {
return xScale(d.x);
})
.attr('y', function(d) {
return yScale(d.y0 + d.y);
})
.attr('height', function(d) {
return yScale(d.y0) - yScale(d.y0 + d.y);
})
.attr('width', xScale.rangeBand());
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div>
<svg width="600" height="300"></svg>
</div>
I am trying to create a visualization to help students that I work with learn about measures of fit, such as r-squared. For R-squared, I want to have both the regression line and a line for the mean of Y on my graph. (My end goal is to have lines between the points and/or lines to represent ESS, TSS, and SSR that students can click to see or not see).
My regression line is working fine, but when I try to add in my average line, it ends up with a strange start and end point and is noticeably NOT a flat line at the average (4.4). I also get the following error in my console:
Error: Invalid value for <path> attribute d="M112,235.71428571428572L194,119.14285714285712L276,NaNL358,NaNL440,NaN"
which corresponds to the line of code:
.attr({
within my avg.append("path") for my avgline (at least, I think that's why I'm specifying there):
svg.append("path")
.datum(avgdataset)
.attr({
d: avgline,
stroke: "green",
"stroke-width": 1,
fill: "none",
"stroke-dasharray": "5,5",
});
I've tried playing around with how avgline is specified to no end (this playing around normally ends up producing no line at all). I've also tried using data instead of datum, to no avail. I'm likely making a really basic mistake, since I'm new to javascript and D3.
Here's all of my code thus far, to put it in context:
//Width and height
var w = 500;
var h = 300;
var padding = 30;
var dataset = [
[1, 1],
[2, 5],
[3, 4],
[4, 7],
[5, 5]
];
//Create scale functions
var xScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {
return d[0];
})])
.range([padding, w - padding * 2]);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {
return d[1];
})])
.range([h - padding, padding]);
var rScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {
return d[1];
})])
.range([2, 5]);
//Define X axis
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(5);
//Define Y axis
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(5);
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Create circles
svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d) {
return xScale(d[0]);
})
.attr("cy", function(d) {
return yScale(d[1]);
})
.attr("r", 4)
.append("svg:title")
.text(function(d) {
return d[0] + "," + d[1];
});;
//average stuff
var sum = 0,
average;
for (var i = 0; i < dataset.length; i++) {
sum += dataset[i][1];
}
average = sum / dataset.length;
console.log(average);
var avgdataset = [
[1, average],
[2, average],
[3, average],
[4, average],
[5, average]
];
console.log(avgdataset);
document.write(avgdataset);
//Create labels
/*svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
return d[0] + "," + d[1];
})
.attr("x", function(d) {
return xScale(d[0]);
})
.attr("y", function(d) {
return yScale(d[1]);
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "red");
*/
//Create X axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
//Create Y axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
var lr = ss.linear_regression().data(dataset).line();
var forecast_x = 20
console.log(lr)
var lrline = d3.svg.line()
.x(function(d, i) {
return xScale(i);
})
.y(function(d, i) {
return yScale(lr(i));
});
svg.append("path")
.datum(Array(dataset.length * forecast_x))
.attr({
d: lrline,
stroke: "black",
"stroke-width": 1,
fill: "none",
"stroke-dasharray": "5,5",
});
var avgline = d3.svg.line()
//.x(function(d, i) { return xScale(i); })
//.y(function(d, i) { return yScale(avgdataset(i)); });
.x(function(d, i) {
return xScale(d[0]);
})
.y(function(d, i) {
return yScale(d[i]);
});
svg.append("path")
.datum(avgdataset)
.attr({
d: avgline,
stroke: "green",
"stroke-width": 1,
fill: "none",
"stroke-dasharray": "5,5",
});
//to get the m and b for the equation line
var mvalue = ss.linear_regression().data(dataset).m();
console.log(mvalue);
var bvalue = ss.linear_regression().data(dataset).b();
console.log(bvalue);
//equation written out
svg.append("text")
.text("Y= " + mvalue + "x + " + bvalue)
.attr("class", "text-label")
.attr("x", 60)
.attr("y", 30);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://raw.github.com/tmcw/simple-statistics/master/src/simple_statistics.js"></script>
Similar to Kaiido, it looks to me that the avgline function was the issue. You were passing in an array of arrays and the x and y weren't accessing the correct part of the array. Most of the examples I've worked with pass an array of objects, so something like:
var data = [ {x: 1, y: 4.4}, {x:2, y:4.4}, etc];
If you construct an object like this you can simple pass this to the avgline which can then elegantly access the correct parts of the data with something like:
var avgline = d3.svg.line() //changed x and y function to reflect changed data
.x(function(d, i) {
return xScale(d.x);
})
.y(function(d, i) {
return yScale(d.y);
});
There are a number of advantages of this. For instance you could ensure that all your data corresponds to this structure and then you would only need one line constructor instead of two.
I think you almost got it, except that avgdataset is not a function but an array.
Simply replace
var avgline = d3.svg.line()
//.x(function(d, i) { return xScale(i); })
//.y(function(d, i) { return yScale(avgdataset(i)); });
.x(function(d, i) {
return xScale(d[0]);
})
.y(function(d, i) {
return yScale(d[i]);
});
with
var avgline = d3.svg.line()
.x(function(d, i) { return xScale(i); })
.y(function(d, i) { return yScale(avgdataset[i][1]); });
//Width and height
var w = 500;
var h = 300;
var padding = 30;
var dataset = [[1, 1], [2, 5], [3, 4], [4, 7], [5, 5]];
//Create scale functions
var xScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[0]; })])
.range([padding, w - padding * 2]);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[1]; })])
.range([h - padding, padding]);
var rScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[1]; })])
.range([2, 5]);
//Define X axis
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(5);
//Define Y axis
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(5);
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Create circles
svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d) {
return xScale(d[0]);
})
.attr("cy", function(d) {
return yScale(d[1]);
})
.attr("r", 4
)
.append("svg:title")
.text(function(d){return d[0] + "," + d[1];});;
//average stuff
var sum = 0, average;
for (var i = 0; i < dataset.length; i++) {
sum += dataset[i][1];
}
average = sum / dataset.length;
console.log(average);
var avgdataset = [[1, average], [2, average], [3, average], [4, average], [5, average]];
console.log(avgdataset);
document.write(avgdataset);
//Create labels
/*svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
return d[0] + "," + d[1];
})
.attr("x", function(d) {
return xScale(d[0]);
})
.attr("y", function(d) {
return yScale(d[1]);
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "red");
*/
//Create X axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
//Create Y axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
var lr = ss.linear_regression().data(dataset).line();
var forecast_x = 20
console.log(lr)
var lrline = d3.svg.line()
.x(function(d, i) { return xScale(i); })
.y(function(d, i) { return yScale(lr(i)); });
svg.append("path")
.datum(Array(dataset.length*forecast_x))
.attr({
d: lrline,
stroke: "black",
"stroke-width": 1,
fill: "none",
"stroke-dasharray": "5,5",
});
var avgline = d3.svg.line()
.x(function(d, i) { return xScale(i); })
.y(function(d, i) { return yScale(avgdataset[i][1]); });
svg.append("path")
.datum(avgdataset)
.attr({
d: avgline,
stroke: "green",
"stroke-width": 1,
fill: "none",
"stroke-dasharray": "5,5",
});
//to get the m and b for the equation line
var mvalue = ss.linear_regression().data(dataset).m();
console.log(mvalue);
var bvalue = ss.linear_regression().data(dataset).b();
console.log(bvalue);
//equation written out
svg.append("text")
.text("Y= " + mvalue + "x + " + bvalue)
.attr("class", "text-label")
.attr("x", 60)
.attr("y", 30);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://raw.github.com/tmcw/simple-statistics/master/src/simple_statistics.js"></script>