d3.js - axis arrowhead direction wrong - d3.js

Arrow head works fine on line draw but direction is wrong on axis!
live_update()
function live_update() {
var data1 = []
var n = 20
for (var i=0;i<=n;i++) {
data1.push({x:i,y:i*i})
}
var data2 = []
for (var i=0;i<=n;i++) {
data2.push({x:i,y:Math.sin(2*Math.PI/n*i)})
}
var toggle = 1
var div = d3.select('body').append('div')
div.append('button')
.text("update")
.on('click',(event,d) => {
console.log('click')
if (toggle == 0) {
update(data1)
toggle = 1
}else{
update(data2)
toggle = 0
}
})
var margin = {top: 10, right: 30, bottom: 30, left: 50},
width = 460 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
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 + ")")
.attr('class','box')
var aw = 6
var ah = 4
svg
.append("defs")
.append("marker")
.attr("id", "arrow")
.attr("refX", aw+1)
.attr("refY", ah/2+1)
.attr("markerWidth", aw+2)
.attr("markerHeight", ah+2)
.attr("orient", "auto")
.append("path")
.attr("d", ['M',1+aw/5,1+ah/2,'L',1,1,1+aw,1+ah/2,1,1+ah,'z'].join(' '));
svg.append('line').attr('class','avline')
var x = d3.scaleLinear().range([0,width]);
var xAxis = d3.axisBottom().scale(x);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.attr("class","myXaxis")
var y = d3.scaleLinear().range([height, 0]);
var yAxis = d3.axisLeft().scale(y);
svg.append("g")
.attr("class","myYaxis")
function update(data) {
var duration = 1000
var xmax = d3.max(data, function(d) { return d.x })
x.domain([d3.min(data,d => d.x), xmax]);
var xaxis = svg.selectAll(".myXaxis").transition()
.duration(duration)
.call(xAxis);
var ymin = d3.min(data,d => d.y)
y.domain([ymin, d3.max(data, function(d) { return d.y }) ]);
var yaxis = svg.selectAll(".myYaxis")
.transition()
.duration(duration)
.call(yAxis);
var frame = d3.select('.box')
frame.selectAll(".lineTest1")
.data([data])
.join("path")
.attr("class","lineTest1")
.transition()
.duration(duration)
.attr("d", d3.line()
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); }))
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 2.5)
.attr("marker-end", "url(#arrow)");
frame.selectAll(".lineTest2")
.data(data)
.join('circle')
.attr('class','lineTest2')
.attr('fill','red')
.transition()
.duration(duration)
.attr('cx',d => x(d.x))
.attr('r',3)
.attr('cy',d => y(d.y))
frame.selectAll(".lineTest3")
.data(data)
.join('path')
.attr('class','lineTest3')
.attr('stroke','gray')
.transition()
.duration(duration)
.attr('d',(d,i) => {
var ax = x(d.x)
var ay = y(d.y)
var bx = ax
var by = y(ymin)
var path = ['M',ax,ay,'L',bx,by]
return path.join(' ')
})
d3.select('.avline')
.attr('stroke','gray')
.transition()
.duration(duration)
.attr('x1',x(0))
.attr('y1',y(0))
.attr('x2',x(xmax))
.attr('y2',y(0))
xaxis.select("path")
.attr("marker-end", "url(#arrow)");
yaxis.select("path")
.attr("marker-end", "url(#arrow)");
}
update(data1)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.0.0/d3.min.js"></script>

Related

d3 horizontal bar chart with background and max value of 100%

I have this single horizontal bar chart and I want to make the following adjustments:
Show the tick value to the right of the bar chart, instead of by the axis.
Show a background for the bar chart scale instead of left and bottom axis.
Current version:
What I'd like to get to:
JS
var data = [
{"yAxis":"score", "xAxis":"72"}
];
// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 80},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// set the ranges
var y = d3.scaleBand()
.range([height, 0])
.padding(0.4);
var x = d3.scaleLinear()
.range([0, width]);
var svg = d3.select(".barChartContainer").append("svg")
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "0 0 960 500")
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Scale the range of the data in the domains
x.domain([0, d3.max(data, function(d){ return d.xAxis; })])
y.domain(data.map(function(d) { return d.yAxis; }));
//y.domain([0, d3.max(data, function(d) { return d.prereqs; })]);
// append the rectangles for the bar chart
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("y", function(d) { return y(d.yAxis); })
.attr("height", y.bandwidth())
.transition()
.duration(1000)
.delay(function(d, i) {
return i * 100
})
.attr("width", function(d) {return x(d.xAxis); } );
// add the x Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).tickValues(d3.range(x.domain()[0], x.domain()[1] + 1, 1))
.tickFormat(d3.format("d"))
);
svg.append("g")
.attr("class", "yAxis")
.call(d3.axisLeft(y));
I got this code from a codepen and I've been trying to adapt it, but it has been breaking so I stopped and was hoping you could help.
Thanks.
For showing the background for the bars, just copy your selection and chose a value of 100% for the rectangles, in a light gray fill:
var backgroundBar = svg.selectAll(null)
.data(data)
.enter()
.append("rect")
//etc...
.attr("width", function(d) {
return x(100);
});
Of course, you'll have to change the domain of the x scale:
var x = d3.scaleLinear()
.domain([0, 100]);
Then, drop both axis and print the labels using a text selection.
Finally, use another text selection for the values:
var values = svg.selectAll(null)
.data(data)
.enter()
.append("text")
//etc...
.text(function(d) {
return +d.xAxis
})
If you want, you can tween the text:
.attrTween("text", function(d) {
var self = this
var i = d3.interpolateNumber(0, +d.xAxis);
return function(t) {
return d3.select(self).text(~~i(t));
}
});
This is the result:
var data = [{
"yAxis": "score",
"xAxis": "72"
}];
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 80
},
width = 500 - margin.left - margin.right,
height = 200 - margin.top - margin.bottom;
var y = d3.scaleBand()
.range([height, 0])
.padding(0.4);
var x = d3.scaleLinear()
.range([0, width])
.domain([0, 100]);
var svg = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 200)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
y.domain(data.map(function(d) {
return d.yAxis;
}));
var backgroundBar = svg.selectAll(null)
.data(data)
.enter()
.append("rect")
.attr("fill", "lightgray")
.attr("y", function(d) {
return y(d.yAxis);
})
.attr("height", y.bandwidth())
.attr("width", function(d) {
return x(100);
});
var bar = svg.selectAll(null)
.data(data)
.enter()
.append("rect")
.attr("class", "bar")
.attr("y", function(d) {
return y(d.yAxis);
})
.attr("height", y.bandwidth())
.transition()
.duration(2000)
.delay(function(d, i) {
return i * 100
})
.attr("width", function(d) {
return x(d.xAxis);
});
var labels = svg.selectAll(null)
.data(data)
.enter()
.append("text")
.attr("y", function(d) {
return y(d.yAxis) + y.bandwidth() / 2;
})
.attr("x", -10)
.attr("text-anchor", "end")
.text(function(d) {
return d.yAxis
});
var values = svg.selectAll(null)
.data(data)
.enter()
.append("text")
.attr("y", function(d) {
return y(d.yAxis) + y.bandwidth() / 2;
})
.attr("x", 10)
.text(function(d) {
return +d.xAxis
})
.transition()
.duration(2000)
.delay(function(d, i) {
return i * 100
})
.attr("x", function(d) {
return x(d.xAxis) + 10;
})
.attrTween("text", function(d) {
var self = this
var i = d3.interpolateNumber(0, +d.xAxis);
return function(t) {
return d3.select(self).text(~~i(t));
}
});
<script src="https://d3js.org/d3.v4.min.js"></script>

d3 center tick and x-axis label when single value

I have the following d3 code:
var json = [
{
date: "05/17",
numTags: 23
}
];
d3.select('summary-graph').selectAll('*').remove();
var svg = d3.select("summary-graph"),
margin = {
top: 20,
right: 30,
bottom: 30,
left: 40
},
width = svg.attr("width") - margin.left - margin.right,
height = svg.attr("height") - margin.top - margin.bottom;
var parseTime = d3.timeParse("%m/%y");
var svg = d3.select("summary-graph").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 + ")");
// Get the data
var data = json;
// format the data
data.forEach(function (d) {
console.log(d);
d.date = parseTime(d.date);
d.numTags = +d.numTags;
});
// set the ranges
var xScale = d3.scaleTime()
.range([0, width])
.domain(d3.extent(data, function (d) {
return d.date;
}))
.nice();
var yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, d3.max(data, function (d) {
return Math.max(d.numTags);
})])
.nice();
// define the 1st line
var tagLine = d3.line()
.x(function (d) {
return xScale(d.date);
})
.y(function (d) {
return yScale(d.numTags);
});
// Axes
var xAxis = d3.axisBottom()
.scale(xScale)
.ticks(json.length)
.tickSizeOuter(0)
.tickFormat(d3.timeFormat('%B %Y'));
var yAxis = d3.axisLeft().scale(yScale);
svg.append("path")
.data([data])
.attr("class", "line")
.style("stroke", "blue")
.attr("d", tagLine);
var points = svg.selectAll(".point")
.data(data)
.enter().append("svg:circle")
.attr("stroke", "green")
.attr("fill", function(d, i) { return "blue" })
.attr("cx", function(d, i) { return xScale(d.date) })
.attr("cy", function(d, i) { return yScale(d.numTags) })
.attr("r", function(d, i) { return 10 });
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.style("font-size","14px");;
// Add the Y Axis
svg.append("g")
.call(yAxis);
Which produces the following visualization:
I'm trying to figure out how to center the tick mark and show the x-axis label when there is only 1 data point like this. At 2 data points, I don't love how it still sets the tick marks at the extreme ends of the x-axis. For 3 data points and above, it looks nice (thanks to .nice() it seems).
Any help?
Based on Gerado's response, I was able to get close. The last sticking point is that the left side of the X-axis now has the month (March) despite no data for that day.
Fixed:
changed .ticks(json.length) to .ticks(d3.timeMonth.every(1))
Since you are using only a single data point, your date scale has a domain in which the lower and upper values are the same:
[
Mon May 01 2017 00: 00: 00 GMT + 1000,
Mon May 01 2017 00: 00: 00 GMT + 1000
]
For putting that circle in the middle of the x axis you have to set different values for the scale's domain.
There are several ways for doing that. My proposed solution here involves verifying if the domain's values are the same...
if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
... and, if they are, changing them. In this case, I'm subtracting one day from the lower limit and adding one day to the upper limit:
if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
xScale.domain([dateLess, dateMore])
}
Check the result:
var json = [{
date: "05/17",
numTags: 23
}];
var margin = {
top: 20,
right: 30,
bottom: 30,
left: 40
},
width = 400,
height = 200;
var parseTime = d3.timeParse("%m/%y");
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 + ")");
// Get the data
var data = json;
// format the data
data.forEach(function(d) {
d.date = parseTime(d.date);
d.numTags = +d.numTags;
});
// set the ranges
var xScale = d3.scaleTime()
.range([0, width])
.domain(d3.extent(data, function(d) {
return d.date;
}))
.nice();
if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
xScale.domain([dateLess, dateMore])
}
var yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, d3.max(data, function(d) {
return Math.max(d.numTags);
})])
.nice();
// define the 1st line
var tagLine = d3.line()
.x(function(d) {
return xScale(d.date);
})
.y(function(d) {
return yScale(d.numTags);
});
// Axes
var xAxis = d3.axisBottom()
.scale(xScale)
.ticks(json.length)
.tickSizeOuter(0)
.tickFormat(d3.timeFormat('%B %Y'));
var yAxis = d3.axisLeft().scale(yScale);
svg.append("path")
.data([data])
.attr("class", "line")
.style("stroke", "blue")
.attr("d", tagLine);
var points = svg.selectAll(".point")
.data(data)
.enter().append("svg:circle")
.attr("stroke", "green")
.attr("fill", function(d, i) {
return "blue"
})
.attr("cx", function(d, i) {
return xScale(d.date)
})
.attr("cy", function(d, i) {
return yScale(d.numTags)
})
.attr("r", function(d, i) {
return 10
});
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.style("font-size", "14px");;
// Add the Y Axis
svg.append("g")
.call(yAxis);
<script src="https://d3js.org/d3.v4.js"></script>
EDIT: As you asked in your edit, when you have two data values my solution will create additional ticks on the limits, which is the expected behaviour:
var json = [{
date: "05/17",
numTags: 23
}, {
date: "05/17",
numTags: 17
}];
var margin = {
top: 20,
right: 30,
bottom: 30,
left: 40
},
width = 400,
height = 200;
var parseTime = d3.timeParse("%m/%y");
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 + ")");
// Get the data
var data = json;
// format the data
data.forEach(function(d) {
d.date = parseTime(d.date);
d.numTags = +d.numTags;
});
// set the ranges
var xScale = d3.scaleTime()
.range([0, width])
.domain(d3.extent(data, function(d) {
return d.date;
}))
.nice();
if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
xScale.domain([dateLess, dateMore])
}
var yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, d3.max(data, function(d) {
return Math.max(d.numTags);
})])
.nice();
// define the 1st line
var tagLine = d3.line()
.x(function(d) {
return xScale(d.date);
})
.y(function(d) {
return yScale(d.numTags);
});
// Axes
var xAxis = d3.axisBottom()
.scale(xScale)
.ticks(json.length)
.tickSizeOuter(0)
.tickFormat(d3.timeFormat('%B %Y'));
var yAxis = d3.axisLeft().scale(yScale);
svg.append("path")
.data([data])
.attr("class", "line")
.style("stroke", "blue")
.attr("d", tagLine);
var points = svg.selectAll(".point")
.data(data)
.enter().append("svg:circle")
.attr("stroke", "green")
.attr("fill", function(d, i) {
return "blue"
})
.attr("cx", function(d, i) {
return xScale(d.date)
})
.attr("cy", function(d, i) {
return yScale(d.numTags)
})
.attr("r", function(d, i) {
return 10
});
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.style("font-size", "14px");;
// Add the Y Axis
svg.append("g")
.call(yAxis);
<script src="https://d3js.org/d3.v4.js"></script>
There are several ways for removing those ticks. One of them is using tickValues:
.tickValues(data.map(function(d){ return d.date}))
Here is the demo:
var json = [{
date: "05/17",
numTags: 23
}, {
date: "05/17",
numTags: 17
}];
var margin = {
top: 20,
right: 30,
bottom: 30,
left: 40
},
width = 400,
height = 200;
var parseTime = d3.timeParse("%m/%y");
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 + ")");
// Get the data
var data = json;
// format the data
data.forEach(function(d) {
d.date = parseTime(d.date);
d.numTags = +d.numTags;
});
// set the ranges
var xScale = d3.scaleTime()
.range([0, width])
.domain(d3.extent(data, function(d) {
return d.date;
}))
.nice();
if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
xScale.domain([dateLess, dateMore])
}
var yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, d3.max(data, function(d) {
return Math.max(d.numTags);
})])
.nice();
// define the 1st line
var tagLine = d3.line()
.x(function(d) {
return xScale(d.date);
})
.y(function(d) {
return yScale(d.numTags);
});
// Axes
var xAxis = d3.axisBottom()
.scale(xScale)
.ticks(json.length)
.tickSizeOuter(0)
.tickValues(data.map(function(d){ return d.date}))
.tickFormat(d3.timeFormat('%B %Y'));
var yAxis = d3.axisLeft().scale(yScale);
svg.append("path")
.data([data])
.attr("class", "line")
.style("stroke", "blue")
.attr("d", tagLine);
var points = svg.selectAll(".point")
.data(data)
.enter().append("svg:circle")
.attr("stroke", "green")
.attr("fill", function(d, i) {
return "blue"
})
.attr("cx", function(d, i) {
return xScale(d.date)
})
.attr("cy", function(d, i) {
return yScale(d.numTags)
})
.attr("r", function(d, i) {
return 10
});
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.style("font-size", "14px");;
// Add the Y Axis
svg.append("g")
.call(yAxis);
<script src="https://d3js.org/d3.v4.js"></script>

Remove old points from line graph in d3

I am trying to create a multi-line graph and updating the data on button click. On each line, I want to highlight the intersection point with a cirlce. Now on button click, I was able to update the line path, but the old highlighted intersection points are not removed from the svgContainer(for eaxmple clicking update2 then update1 do not removes the last set of circles which are not connected to any line).
<input type="button" onclick="update1()" value="Update" />
<input type="button" onclick="update2()" value="UpdateDimension_T" />
<div id="outputViz">
</div>
<script type="text/javascript">
var data = [
[{'index':1,'score':0},{'index':2,'score':5},{'index':3,'score':10},{'index':4,'score':0},{'index':5,'score':6}],
[{'index':1,'score':1},{'index':2,'score':6},{'index':3,'score':11},{'index':4,'score':1},{'index':5,'score':7}],
[{'index':1,'score':2},{'index':2,'score':7},{'index':3,'score':12},{'index':4,'score':2},{'index':5,'score':8}],
[{'index':1,'score':3},{'index':2,'score':8},{'index':3,'score':13},{'index':4,'score':3},{'index':5,'score':9}],
[{'index':1,'score':4},{'index':2,'score':9},{'index':3,'score':14},{'index':4,'score':4},{'index':5,'score':10}]
];
var data_O = [
[{'index':1,'score':1},{'index':2,'score':6},{'index':3,'score':11},{'index':4,'score':1},{'index':5,'score':7},{'index':6,'score':12}],
[{'index':1,'score':2},{'index':2,'score':7},{'index':3,'score':12},{'index':4,'score':2},{'index':5,'score':8},{'index':6,'score':13}],
[{'index':1,'score':3},{'index':2,'score':8},{'index':3,'score':13},{'index':4,'score':3},{'index':5,'score':9},{'index':6,'score':14}],
[{'index':1,'score':4},{'index':2,'score':9},{'index':3,'score':14},{'index':4,'score':4},{'index':5,'score':10},{'index':6,'score':15}],
[{'index':1,'score':5},{'index':2,'score':10},{'index':3,'score':15},{'index':4,'score':5},{'index':5,'score':11},{'index':6,'score':16}]
];
var data_T = [
[{'index':1,'score':5},{'index':2,'score':10},{'index':3,'score':15},{'index':4,'score':5},{'index':5,'score':12},{'index':6,'score':20},{'index':7,'score':15}],
[{'index':1,'score':6},{'index':2,'score':11},{'index':3,'score':16},{'index':4,'score':6},{'index':5,'score':13},{'index':6,'score':21},{'index':7,'score':16}],
[{'index':1,'score':7},{'index':2,'score':12},{'index':3,'score':17},{'index':4,'score':7},{'index':5,'score':14},{'index':6,'score':22},{'index':7,'score':17}],
[{'index':1,'score':8},{'index':2,'score':13},{'index':3,'score':18},{'index':4,'score':8},{'index':5,'score':15},{'index':6,'score':23},{'index':7,'score':18}],
[{'index':1,'score':9},{'index':2,'score':14},{'index':3,'score':19},{'index':4,'score':9},{'index':5,'score':16},{'index':6,'score':24},{'index':7,'score':19}]
];
var colors = [
'steelblue',
'green',
'red',
'purple',
'black'
];
var dataset = ["","Or","Se","Tr","De","Cc"];
var dataset_O = ["","O_1","O_2","O_3","O_4","O_5","O_6"];
var dataset_T = ["","T_1","T_2","T_3","T_4","T_5","T_6","T_7"];
var margin = {top: 20, right: 30, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
padding = 30;
var x = d3.scale.linear()
.domain([0, dataset.length])
.range([0, width]);
var y = d3.scale.linear()
.domain([-1, 16])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.tickFormat(function(d) { return dataset[d]; })
.tickSize(-height)
.tickPadding(10)
.tickSubdivide(false)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.tickPadding(10)
.tickSize(-width)
.tickSubdivide(false)
.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 + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "y axis")
.append("text")
.attr("class", "axis-label")
.attr("transform", "rotate(-90)")
.attr("y", (-margin.left) + 10)
.attr("x", -height/2)
.text('Axis Label');
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var line = d3.svg.line()
.interpolate("linear")
.x(function(d) { return x(d.index); })
.y(function(d) { return y(d.score); });
svg.selectAll('.line')
.data(data)
.enter()
.append("path")
.attr("class", "line")
.attr('stroke', function(d,i){
return colors[i%colors.length];
})
.attr("d", line);
var points = svg.selectAll('.dots')
.data(data)
.enter()
.append("g")
.attr("class", "dots")
points.selectAll('.dot')
.data(function(d, index){
var a = [];
d.forEach(function(point,i){
a.push({'index': index, 'point': point});
});
return a;
})
.enter()
.append('circle')
.attr('class','dot')
.attr("r", 2.5)
.attr('fill', function(d,i){
return colors[d.index%colors.length];
})
.attr("transform", function(d) {
return "translate(" + x(d.point.index) + "," + y(d.point.score) + ")"; }
);
function update1(){
var x = d3.scale.linear()
.domain([0, dataset_O.length])
.range([0, width]);
var y = d3.scale.linear()
.domain([-1, 16])
.range([height, 0]).nice();
xAxis = d3.svg.axis()
.scale(x)
.tickFormat(function(d) { return dataset_O[d]; })
.tickSize(-height)
.tickPadding(10)
.tickSubdivide(false)
.orient("bottom");
yAxis = d3.svg.axis()
.scale(y)
.tickPadding(10)
.tickSize(-width)
.tickSubdivide(false)
.orient("left");
var line = d3.svg.line()
.interpolate("linear")
.x(function(d) { return x(d.index); })
.y(function(d) { return y(d.score); });
svg.selectAll('.line')
.data(data_O)
.transition(750)
.attr("d", line)
.attr("class", "line");
// change the x axis
svg.select(".x.axis").call(xAxis);
// change the y axis
svg.select(".y.axis").call(yAxis);
var points = svg.selectAll('.dots').data(data_O);
//UPDATE - HANDLE the current count
points.selectAll('.dot')
.data(function(d, index){
var a = [];
d.forEach(function(point,i){
a.push({'index': index, 'point': point});
});
return a;
})
.attr("transform", function(d) {
return "translate(" + x(d.point.index) + "," + y(d.point.score) + ")";
});
//ENTER - add the newly added count
points.selectAll('.dot')
.data(function(d, index){
var a = [];
d.forEach(function(point,i){
a.push({'index': index, 'point': point});
});
return a;
})
.enter()
.append('circle')
.attr('class','dot')
.attr("r", 2.5)
.attr('fill', function(d,i){
return colors[d.index%colors.length];
})
.attr("transform", function(d) {
return "translate(" + x(d.point.index) + "," + y(d.point.score) + ")";
});
d3.selectAll('g.dots').data(data_O).exit().remove();
}
function update2(){
var x = d3.scale.linear()
.domain([0, dataset_T.length])
.range([0, width]);
//var yExtents = d3.extent(d3.merge(data_T), function (d) { return d.score; });
var y = d3.scale.linear()
.domain([-1, 29])
.range([height, 0]).nice();
xAxis = d3.svg.axis()
.scale(x)
.tickFormat(function(d) { return dataset_T[d]; });
var line = d3.svg.line()
.interpolate("linear")
.x(function(d) { return x(d.index); })
.y(function(d) { return y(d.score); });
svg.selectAll('.line')
.data(data_T)
.transition(750)
.attr("d", line)
.attr("class", "line");
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
var points = svg.selectAll('.dots').data(data_T);
//ENTER - add the newly added count
points.selectAll('.dot')
.data(function(d, index){
var a = [];
d.forEach(function(point,i){
a.push({'index': index, 'point': point});
});
return a;
})
.enter()
.append('circle')
.attr('class','dot')
.attr("r", 2.5)
.attr('fill', function(d,i){
return colors[d.index%colors.length];
})
.attr("transform", function(d) {
return "translate(" + x(d.point.index) + "," + y(d.point.score) + ")";
});
//UPDATE - HANDLE the current count
points.selectAll('.dot')
.data(function(d, index){
var a = [];
d.forEach(function(point,i){
a.push({'index': index, 'point': point});
});
return a;
})
.attr("transform", function(d) {
return "translate(" + x(d.point.index) + "," + y(d.point.score) + ")";
});
}
</script>
Here is the link to fiddle:
https://jsfiddle.net/aakashjain/1dc57aL7/1/
You'll need an "exit" selection:
points.selectAll('.dot')
.data(function(d, index){
var a = [];
d.forEach(function(point,i){
a.push({'index': index, 'point': point});
});
return a;
})
.exit()
.remove();
Here is the update fiddle:. https://jsfiddle.net/1dc57aL7/2/
(Just a tip: you have a lot of duplicated code here. Your "update1" and "update2" functions could be way smaller)

Set arbitrary center in streamgraph offset

I have data in a streamgraph stack layout and the desired aesthetic I'm after is to assign an arbitrary series as the center line(s). Series above those lines (as determined by their index in the data) will stack on top and series below that line will stack below.
Here's a jsFidde.
In this example, I'd like the MS and the RC series to be single horizontal lines with the other groups stacked above and below them, respectively. (As opposed to the data index, I could also set the middle series based on some data attribute, in this example, oldest date would make sense.)
I think the solution would require passing my own offset function but I'm having a hard time figuring out how the built-in ones do what they do.
HTML
<div class="chart">
JS
// Adapted from https://gist.github.com/WillTurman/4631136
var data = [
{"key":"DJ","value":0,"date":"1/8/13"},
{"key":"DJ","value":0,"date":"1/9/13"},
{"key":"DJ","value":0,"date":"1/10/13"},
{"key":"DJ","value":1,"date":"1/11/13"},
{"key":"DJ","value":1,"date":"1/12/13"},
{"key":"MS","value":0,"date":"1/8/13"},
{"key":"MS","value":1,"date":"1/9/13"},
{"key":"MS","value":1,"date":"1/10/13"},
{"key":"MS","value":1,"date":"1/11/13"},
{"key":"MS","value":1,"date":"1/12/13"},
{"key":"RC","value":0,"date":"1/8/13"},
{"key":"RC","value":1,"date":"1/9/13"},
{"key":"RC","value":1,"date":"1/10/13"},
{"key":"RC","value":1,"date":"1/11/13"},
{"key":"RC","value":1,"date":"1/12/13"},
{"key":"CG","value":0,"date":"1/8/13"},
{"key":"CG","value":0,"date":"1/9/13"},
{"key":"CG","value":0,"date":"1/10/13"},
{"key":"CG","value":0,"date":"1/11/13"},
{"key":"CG","value":1,"date":"1/12/13"},
{"key":"RI","value":0,"date":"1/8/13"},
{"key":"RI","value":0,"date":"1/9/13"},
{"key":"RI","value":0,"date":"1/10/13"},
{"key":"RI","value":0,"date":"1/11/13"},
{"key":"RI","value":1,"date":"1/12/13"}
]
chart(data, "pink");
var datearray = [];
var colorrange = [];
function chart(data, color) {
if (color == "blue") {
colorrange = ["#045A8D", "#2B8CBE", "#74A9CF", "#A6BDDB", "#D0D1E6", "#F1EEF6"];
}
else if (color == "pink") {
colorrange = ["#980043", "#DD1C77", "#DF65B0", "#C994C7", "#D4B9DA", "#F1EEF6"];
}
else if (color == "orange") {
colorrange = ["#B30000", "#E34A33", "#FC8D59", "#FDBB84", "#FDD49E", "#FEF0D9"];
}
strokecolor = colorrange[0];
var format = d3.time.format("%m/%d/%y");
var margin = {top: 20, right: 40, bottom: 30, left: 30};
var width = document.body.clientWidth - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;
var tooltip = d3.select("body")
.append("div")
.attr("class", "remove")
.style("position", "absolute")
.style("z-index", "20")
.style("visibility", "hidden")
.style("top", "30px")
.style("left", "55px");
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height-10, 0]);
var z = d3.scale.ordinal()
.range(colorrange);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(d3.time.weeks);
var yAxis = d3.svg.axis()
.scale(y);
var yAxisr = d3.svg.axis()
.scale(y);
var stack = d3.layout.stack()
.offset("silhouette")
.values(function(d) { return d.values; })
.x(function(d) { return d.date; })
.y(function(d) { return d.value; });
var nest = d3.nest()
.key(function(d) { return d.key; });
var area = d3.svg.area()
.interpolate("linear")
.x(function(d) { return x(d.date); })
.y0(function(d) { return y(d.y0); })
.y1(function(d) { return y(d.y0 + d.y); });
var svg = d3.select(".chart").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 + ")");
data.forEach(function(d) {
d.date = format.parse(d.date);
d.value = +d.value;
});
var layers = stack(nest.entries(data));
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]);
svg.selectAll(".layer")
.data(layers)
.enter().append("path")
.attr("class", "layer")
.attr("d", function(d) { return area(d.values); })
.style("fill", function(d, i) { return z(i); });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + width + ", 0)")
.call(yAxis.orient("right"));
svg.append("g")
.attr("class", "y axis")
.call(yAxis.orient("left"));
svg.selectAll(".layer")
.attr("opacity", 1)
.on("mouseover", function(d, i) {
svg.selectAll(".layer").transition()
.duration(250)
.attr("opacity", function(d, j) {
return j != i ? 0.6 : 1;
})})
.on("mousemove", function(d, i) {
mousex = d3.mouse(this);
mousex = mousex[0];
var invertedx = x.invert(mousex);
invertedx = invertedx.getMonth() + invertedx.getDate();
var selected = (d.values);
for (var k = 0; k < selected.length; k++) {
datearray[k] = selected[k].date
datearray[k] = datearray[k].getMonth() + datearray[k].getDate();
}
mousedate = datearray.indexOf(invertedx);
pro = d.values[mousedate].value;
d3.select(this)
.classed("hover", true)
.attr("stroke", strokecolor)
.attr("stroke-width", "0.5px"),
tooltip.html( "<p>" + d.key + "<br>" + pro + "</p>" ).style("visibility", "visible");
})
.on("mouseout", function(d, i) {
svg.selectAll(".layer")
.transition()
.duration(250)
.attr("opacity", "1");
d3.select(this)
.classed("hover", false)
.attr("stroke-width", "0px"), tooltip.html( "<p>" + d.key + "<br>" + pro + "</p>" ).style("visibility", "hidden");
})
var vertical = d3.select(".chart")
.append("div")
.attr("class", "remove")
.style("position", "absolute")
.style("z-index", "19")
.style("width", "1px")
.style("height", "380px")
.style("top", "10px")
.style("bottom", "30px")
.style("left", "0px")
.style("background", "#fff");
d3.select(".chart")
.on("mousemove", function(){
mousex = d3.mouse(this);
mousex = mousex[0] + 5;
vertical.style("left", mousex + "px" )})
.on("mouseover", function(){
mousex = d3.mouse(this);
mousex = mousex[0] + 5;
vertical.style("left", mousex + "px")});
}

Multiseries graph using d3.v2.js

We are plotting a multilinear graph using d3.v2.js .
We are using ordinal scale for x-axis and linear scale for y-axis as we have labels(string) to be shown in x-axis
and numbers to be shown in y-axis.
In some cases graph appears to be fine , but in some cases it plots x-axis and y-axis independently and y-axis values are not in sync with x-axis values.
Also plotting starts from 0 instead of first x-axis value.
Any pointers to this issue would be of great help.
Thanks in advance.
Please find the code below.
function plotMOAGraph(data , sigPathways){
var margin = {top: 20, right: 80, bottom: 30, left: 100},
width = 960 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var x = d3.scale.ordinal(
(d3.range(0,sigPathways.length))).rangeBands([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 line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.pathway); })
.y(function(d) { return y(d.score); });
var svg = d3.select("#graphDiv").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", 450 + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "pathway"; }));
var entityNames = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {pathway: d.pathway, score: +d[name]};
})
};
});
x.domain(sigPathways);
y.domain([
d3.min(entityNames, function(c) { return d3.min(c.values, function(v) { return v.score; }); }),
d3.max(entityNames, function(c) { return d3.max(c.values, function(v) { return v.score; }); })
]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("dy", "9em")
.attr("dx","40em")
.style("text-anchor", "end")
.text("Pathways");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "-4em")
.style("text-anchor", "end")
.text("Pathway Scores");
var tooltip = d3.select("#graphDiv")
.append("div")
.style("visibility", "hidden")
;
var rotateXAxis = function(d) {
var name = d.substr(0, 15);
if(name !== d) {
name = name + " ... ";
}
var el = d3.select(this);
el.text('').attr("transform", "rotate(-45)").attr("text-anchor", "end").on("mouseover", showTooltip).on("mouseout",hideTooltip);
var tspan = el.append('tspan').text(name);
tspan.attr('x', 0).attr('dy', '0');
};
svg.selectAll('g.x.axis g text').each(rotateXAxis);
function showTooltip(d) {
tooltip.text(d).style("position","absolute")
.style("top", (d3.event.pageY)-10+"px")
.style("left", (d3.event.pageX)-300+"px")
.style("visibility", "visible")
.style("font-size", "12px");
}
function hideTooltip() {
tooltip.style("visibility", "hidden");
}
var entityName = svg.selectAll(".entityName")
.data(entityNames)
.enter().append("g")
.attr("class", "entityName");
entityName.append("path")
.attr("class", "line")
.attr("d", function(d) {
return line(d.values); })
.style("stroke", function(d) {return color(d.name); });
entityName.append("text")
.datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.pathway) + "," + y(d.value.score) + ")"; })
.attr("x", 3)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
}

Resources