D3js Angular Directive Lots of Repeating Code on Re-Rendering - javascript

I'm a little new to using D3, and trying to create a scatter-plot. I seem to have lots of repeating code due for window resize, and rendering on data updates. I'm not sure if it's the nature of D3 and updating data or if I'm overlooking a pretty obvious update pattern.
The directive seems lengthy, but only because I have similar code repeated in updateWindow() (for browser resize), render (for the initial rendering and inserting SVG elements, and update (for updating the element attributes when the data changes). Here is my directive, currently:
app.directive('scatterPlot', function ($window, inputService, dataHandler) {
return {
restrict: 'E',
scope: {
input: '=',
display: '='
},
link: function (scope, element, array) {
var container = angular.element(document.querySelector('section.output'))[0];
var filterCount = 0;
var data = undefined;
// ********** ********** ************ //
// ********* ************ *********** //
// ******** ************** ********** //
// ******* **************** ********* //
// ******* WATCH AND RENDER ********* //
scope.$on('inputChange', function(event, isDeleted, isEmpty, isComplete, id, value) {
// CHECK FOR MATCHES //
console.log('event: ', event);
console.log('isDeleted: ', isDeleted, ', isEmpty: ', isEmpty, ', isComplete: ', isComplete, ', id: ', id, ', value: ', value);
if (isDeleted) {
filterCount -= 1;
console.log('filterCount: ', filterCount);
} else {
if (filterCount == 0) {
dataHandler.matchQuery(id, value).then(function(matches) {
data = matches;
filterCount += 1;
return render(matches);
});
} else {
dataHandler.matchQuery(id, value, data).then(function(matches) {
data = matches;
filterCount += 1;
if (filterCount > 0) {
return update(data);
}
});
}
}
});
var formatAsMillions = d3.format('$' + "s");
var formatAsYears = function(d) { return Math.floor(d/365) + ' Years'; };
function update(data) {
var el = element[0];
var margin = {
top: container.clientHeight / 12,
right: container.clientWidth / 7,
bottom: container.clientHeight / 5,
left: container.clientWidth / 11
};
var w = (container.clientWidth - margin.left - margin.right) * 0.9;
var h = (container.clientHeight - margin.top - margin.bottom) * 0.9;
var input = data;
var xScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ctc"]; })])
.range([0, w])
.nice();
var yScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ttc"]; })])
.range([h, 0])
.nice();
var rScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["effective"]; })])
.range([2, 10]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.ticks(5)
.tickFormat(formatAsMillions);
var max= xScale.domain()[1];
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left')
.ticks(8)
.tickFormat(formatAsYears)
.tickFormat(function (days) {
if (max < 50) {
return d3.format("2.1f")(days) + " d";
}
else if (max >= 50 && max < 100) {
return d3.format("2.1f")(days/7) + " w";
}
else if (max >= 100 && max < 500) {
return d3.format("2.1f")(days/(365/12)) + " m";
}
else if (max >= 500){
return d3.format("2.1f")(days/365) + " y";
}
});
// *********** //
// SVG ELEMENT //
var svg = d3.select('svg')
.attr('class', 'scatter')
.attr('width', w + margin.left + margin.right)
.attr('height', h + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// add X axis
d3.select('.xAxis')
.data(input)
.remove()
.exit()
svg.append('g')
.attr('class', 'xAxis')
.attr('transform', 'translate(0,' + h + ')')
.call(xAxis);
// add Y axis
d3.select('.yAxis')
.data(input)
.remove()
.exit()
svg.append('g')
.attr('class', 'yAxis')
.call(yAxis);
// DATA JOIN
// Join new data with old elements, if any.
var circle = d3.selectAll('circle')
.data(input, function(d) {return d.id;})
.remove()
.exit();
// UPDATE
// Update old elements as needed.
circle.attr('class', 'update')
.transition()
.duration(300)
.attr('cx', function(d) { return xScale(d["ctc"]); })
.attr('cy', function(d) { return yScale(d["ttc"]); })
.attr('r', function(d) { return rScale(d["effective"]); });
}
function render(matches) {
console.log(matches.length);
// ********** ********** ************ //
// ********* ************ *********** //
// ******** ************** ********** //
// ******** **************** ******** //
// ******** BASIC ATTRIBUTES ******** //
var input = matches;
var el = element[0];
var effectiveScale = d3.scale.linear()
.domain([1, d3.max(input, function(d) {return d["effective"]; }) ])
.range(["#35ca98", "#029765", "#006432", "#001700"]);
var margin = {
top: container.clientHeight / 12,
right: container.clientWidth / 7,
bottom: container.clientHeight / 5,
left: container.clientWidth / 11
};
var w = (container.clientWidth - margin.left - margin.right) * 0.9;
var h = (container.clientHeight - margin.top - margin.bottom) * 0.9;
var xScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ctc"]; })])
.range([0, w])
.nice();
var yScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ttc"]; })])
.range([h, 0])
.nice();
var rScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["effective"]; })])
.range([2, 15]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.ticks(5)
.tickFormat(formatAsMillions);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left')
.ticks(8)
.tickFormat(formatAsYears);
// *********** //
// SVG ELEMENT //
var svg = d3.select(el)
.append('svg')
.attr('class', 'scatter')
.attr('width', w + margin.left + margin.right)
.attr('height', h + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// add X axis
svg.append('g')
.attr('class', 'xAxis')
.attr('transform', 'translate(0,' + h + ')')
.call(xAxis);
// add Y axis
svg.append('g')
.attr('class', 'yAxis')
.call(yAxis);
//Create the tooltip label
var tooltip = d3.select('body')
.append('div')
.attr('class', 'tooltip')
.style('position', 'absolute')
.style('z-index', '10')
.style('visibility', 'hidden')
// add circles in group
var circles = svg.append('g')
.attr('class','circles')
.attr('clip-path','url(#chart-area)');
// add individual circles
var circle = circles.selectAll('circle')
.data(input, function(d) {return d.id;})
.enter()
.append('circle')
.attr('class', 'circle')
.attr('cx', function(d) { return xScale(d["ctc"]); })
.attr('cy', function(d) { return yScale(d["ttc"]); })
.attr('r', function(d) { return rScale(d["effective"]); })
.attr('fill', function(d, i) { return effectiveScale(d["effective"])})
.on('mouseover', function(d) {
tooltip.style('visibility', 'visible');
return tooltip.text(d["technology"]);
})
.on("mousemove", function(){ return tooltip.style("top",
(d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");})
// NEW SCOPE VALUE ON CLICK //
.on('click', function(d) {
scope.display = d;
console.log(d);
scope.$apply();
return d;
});
// append clip path
svg.append('clipPath')
.attr('id','chart-area')
.append('rect')
.attr('class', 'rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', w)
.attr('height', h);
// add text
svg.selectAll('text')
.data(input, function(d) {return d.id;})
.enter()
.append('text')
.attr('class', 'label')
.attr('clip-path','url(#chart-area)')
.attr('x', function(d) { return xScale(d["ctc"]); })
.attr('y', function(d) { return yScale(d["ttc"]) - rScale(d["effective"]) - 9; })
//.text(function(d) { return d["technology"]; });
// ********** ********** ************ //
// ********* ************ *********** //
// ******** ************** ********** //
// ******** ************** ********** //
// ******** UPDATE WINDOW *********** //
angular.element($window).bind('resize', function() {
updateWindow();
});
function updateWindow() {
var w = container.clientWidth - margin.left - margin.right;
var h = (container.clientHeight - margin.top - margin.bottom) * 0.9;
var xScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ctc"]; })])
.range([0, w])
.nice();
var yScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ttc"]; })])
.range([h, 0])
.nice();
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.ticks(5)
.tickFormat(formatAsMillions);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left')
.ticks(8)
.tickFormat(formatAsYears);
// add X axis
d3.select('.xAxis')
.attr('transform', 'translate(0,' + h + ')')
.call(xAxis);
// add Y axis
d3.select('.yAxis')
.call(yAxis);
/// adjust svg element width/height
d3.select('.scatter')
.attr('width', w + margin.left + margin.right)
.attr('height', h + margin.top + margin.bottom)
.select('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', w + margin.left + margin.right)
.attr('height', h + margin.top + margin.bottom);
// adjust circle location
d3.select('.circles')
.attr('clip-path','url(#chart-area)')
.selectAll('circle')
.attr('cx', function(d) { return xScale(d["ctc"]); })
.attr('cy', function(d) { return yScale(d["ttc"]); })
.attr('r', function(d) { return rScale(d["effective"]); });
// adjust clip path
d3.select('.rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', w)
.attr('height', h);
}
};
}
};
});
Is there a common update pattern for reusing some of the same declarations here?

Related

D3 js tooltip violin plot

I have made a violin plot in D3.js with the following code:
<script src="https://d3js.org/d3.v4.js"></script>`
<div id="power"></div>
<script>
var margin = {top: 120, right: 100, bottom: 80, left: 100},
width = 2600 - margin.left - margin.right,
height = 620 - margin.top - margin.bottom;
var svg = d3.select("#power")
.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 + ")");
// Read the data and compute summary statistics for each
d3.csv("static/csv/violinsummary.csv", function (data) {
// Show the X scale
var x = d3.scaleBand()
.range([0, width])
.domain(["2017-09", "2017-10", "2018-02", "2018-03"])
.paddingInner(0)
.paddingOuter(.5);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Show the Y scale
var y = d3.scaleLinear()
.domain([80, 105])
.range([height, 0]);
svg.append("g").call(d3.axisLeft(y));
// Features of density estimate
var kde = kernelDensityEstimator(kernelEpanechnikov(.2), y.ticks(50));
// Compute the binning for each group of the dataset
var sumstat = d3.nest()
.key(function (d) {
return d.DATE;
})
.rollup(function (d) { // For each key..
input = d.map(function (g) {
return g.Power;
});
density = kde(input); // And compute the binning on it.
return (density);
})
.entries(data);
var maxNum = 0;
for (i in sumstat) {
allBins = sumstat[i].value;
kdeValues = allBins.map(function (a) {
return a[1]
});
biggest = d3.max(kdeValues);
if (biggest > maxNum) {
maxNum = biggest
}
}
// The maximum width of a violin must be x.bandwidth = the width dedicated to a group
var xNum = d3.scaleLinear()
.range([0, x.bandwidth()])
.domain([-maxNum, maxNum]);
svg
.selectAll("myViolin")
.data(sumstat)
.enter() // So now we are working group per group
.append("g")
.attr("transform", function (d) {
return ("translate(" + x(d.key) + " ,0)")
}) // Translation on the right to be at the group position
.append("path")
.datum(function (d) {
return (d.value)
}) // So now we are working density per density
.style("opacity", .7)
.style("fill", "#317fc8")
.attr("d", d3.area()
.x0(function (d) {
return (xNum(-d[1]))
})
.x1(function (d) {
return (xNum(d[1]))
})
.y(function (d) {
return (y(d[0]))
})
.curve(d3.curveCatmullRom));
});
function kernelDensityEstimator(kernel, X) {
return function (V) {
return X.map(function (x) {
return [x, d3.mean(V, function (v) {
return kernel(x - v);
})];
});
}
}
function kernelEpanechnikov(k) {
return function (v) {
return Math.abs(v /= k) <= 1 ? 0.75 * (1 - v * v) / k : 0;
};
}
</script>
Data (violinsummary.csv):
Power,DATE
89.29,2017-09
89.9,2017-09
91.69,2017-09
89.23,2017-09
91.54,2017-09
88.49,2017-09
89.15,2017-09
90.85,2017-09
89.59,2017-09
93.38,2017-10
92.41,2017-10
90.65,2017-10
91.07,2017-10
90.13,2017-10
91.73,2017-10
91.09,2017-10
93.21,2017-10
91.62,2017-10
89.58,2017-10
90.59,2017-10
92.57,2017-10
89.99,2017-10
90.59,2017-10
88.12,2017-10
91.3,2017-10
89.59,2018-02
91.9,2018-02
87.83,2018-02
90.36,2018-02
91.38,2018-02
91.56,2018-02
91.89,2018-02
90.95,2018-02
90.15,2018-02
90.24,2018-02
94.04,2018-02
85.4,2018-02
88.47,2018-02
92.3,2018-02
92.46,2018-02
92.26,2018-02
88.78,2018-02
90.13,2018-03
89.95,2018-03
92.98,2018-03
91.94,2018-03
90.29,2018-03
91.2,2018-03
94.22,2018-03
90.71,2018-03
93.03,2018-03
91.89,2018-03
I am trying to make a tooltip for each violin that shows the median and mean upon hover. I cannot figure out how to make the tooltip show up.
I know I need to do something like this with mouseover and mouseout but I'm not sure...
var tooltip = d3.select('#power')
.append('div')
.attr('class', 'tooltip')
.style("opacity", 0);
Any tips/guidance would be very appreciated.
You can implement the tooltip functionality by following two steps.
Step 1:
Initialize the tooltip container which already you did I guess.
var tooltip = svg.append("g")
.attr("class", "tooltip")
.style("display", "none");
tooltip.append("rect")
.attr("width", 30)
.attr("height", 20)
.attr("fill", "white")
.style("opacity", 0.5);
tooltip.append("text")
.attr("x", 15)
.attr("dy", "1.2em")
.style("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold");
Step 2:
Change the visibility property of the tooltip in the mouseover, mouseout event of the element. In your case, it's myViolin
.on("mouseover", function() {
tooltip.style("display", null);
})
.on("mouseout", function() {
tooltip.style("display", "none");
})
.on("mousemove", function(d) {
var xPosition = d3.mouse(this)[0] - 15;
var yPosition = d3.mouse(this)[1] - 25;
tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
tooltip.select("text").text(d.y);
});
Here is the implementation of tooltip jsFiddle
Hope it helps :)

border for d3 stack bar chart on selection

Trying to implement border for selected bar in d3 stack bar chart. Here the first bar's top border goes behind second bar a little bit. How to avoid this?
var svg, height, width, margin, parentWidth, parentHeight;
// container size
parentWidth = 700;
parentHeight = 500;
margin = {top: 50, right: 20, bottom: 35, left: 30};
width = parentWidth - margin.left - margin.right;
height = parentHeight - margin.top - margin.bottom;
var selectedSection = window.sessionStorage.getItem('selectedSection');
// data
var dataset = [{"label":"DEC","Set Up":{"count":12,"id":1,"label":"Set Up","year":"2016","graphType":"setup"},"Not Set Up":{"count":12,"id":0,"label":"Not Set Up","year":"2016","graphType":"setup"}},{"label":"JAN","Set Up":{"count":6,"id":1,"label":"Set Up","year":"2017","graphType":"setup"},"Not Set Up":{"count":21,"id":0,"label":"Not Set Up","year":"2017","graphType":"setup"}},{"label":"FEB","Set Up":{"count":1,"id":1,"label":"Set Up","year":"2017","graphType":"setup"},"Not Set Up":{"count":2,"id":0,"label":"Not Set Up","year":"2017","graphType":"setup"}},{"label":"MAR","Set Up":{"count":0,"id":1,"label":"Set Up","year":"2017","graphType":"setup"},"Not Set Up":{"count":0,"id":0,"label":"Not Set Up","year":"2017","graphType":"setup"}},{"label":"APR","Set Up":{"count":0,"id":1,"label":"Set Up","year":"2017","graphType":"setup"},"Not Set Up":{"count":0,"id":0,"label":"Not Set Up","year":"2017","graphType":"setup"}}];
// x cord
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.2);
// color helper
var colorRange = d3.scale.category20();
var color = d3.scale.ordinal()
.range(colorRange.range());
// x axis
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');
var colors = ['#50BEE9', '#30738C'];
// Set SVG
svg = d3.select('#chart')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom )
.attr('class', 'setup')
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
color.domain(d3.keys(dataset[0]).filter(function(key) { return key !== 'label'; }));
dataset.forEach(function(d) {
var y0 = 0;
d.values = color.domain().map(function(name) {
return {
name: name,
y0: y0,
y1: y0 += +d[name].count,
patientStatus:d[name].id,
graphType:d[name].graphType,
fromDate:{
month:d.label,
year:d[name].year
},
toDate:{
month:d.label,
year:d[name].year
}
};
});
d.total = d.values[d.values.length - 1].y1;
});
var y = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {
return d.total;
})])
.range([height, 0]);
var ticks = y.ticks(),
lastTick = ticks[ticks.length-1];
var newLastTick = lastTick + (ticks[1] - ticks[0]);
if (lastTick<y.domain()[1]){
ticks.push(lastTick + (ticks[1] - ticks[0]));
}
// adjust domain for further value
y.domain([y.domain()[0], newLastTick]);
// y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient('left')
.tickSize(-width, 0, 0)
.tickFormat(d3.format('d'))
.tickValues(ticks);
x.domain(dataset.map(function(d) { return d.label; }));
y.domain([0, d3.max(dataset, function(d) { return d.total; })]);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
svg.append('g')
.attr('class', 'y axis')
.call(yAxis);
var bar = svg.selectAll('.label')
.data(dataset)
.enter().append('g')
.attr('class', 'g')
.attr('id', function(d, i) {
return i;
})
.attr('transform', function(d) { return 'translate(' + x(d.label) + ',0)'; });
var barEnter = bar.selectAll('rect')
.data(function(d) { return d.values; })
.enter();
barEnter.append('rect')
.attr('width', x.rangeBand())
.attr('y', function(d) {
return y(d.y1);
})
.attr('class', function(d, i){
return 'bar';
})
.attr('height', function(d) { return y(d.y0) - y(d.y1); })
.style('fill', function(d,i) { return colors[i]; })
.on('click', function(d, i) {
d3.selectAll('.bar').classed('selected', false);
d3.select(this)
.classed('bar selected', true);
});
barEnter.append('text')
.text(function(d) {
var calcH = y(d.y0) - y(d.y1);
var inText = (d.y1-d.y0);
if(calcH >= 20) {
return inText;
} else {
return '';
}
})
.attr('class','inner-text')
.attr('y', function(d) { return y(d.y1)+(y(d.y0) - y(d.y1))/2 + 5; })
.attr('x', function(){
return (x.rangeBand()/2) - 10;
});
svg
.select('.y')
.selectAll('.tick')
.filter(function (d) {
return d % 1 !== 0;
})
.style('display','none');
svg
.select('.y')
.selectAll('.tick')
.filter(function (d) {
return d === 0;
})
.select('text')
.style('display','none');
JSFiddle
JSFiddle with d3 v4
In a SVG, just like a real painter putting ink to a white canvas, the element that is painted last stays on top.
Right now, the behaviour you're seeing is the expected one, because each stacked bar (rectangle) is in a different <g> element, and the groups, of course, have a given order in the SVG structure.
The solution involves just one line:
d3.select(this.parentNode).raise();
What this line does is selecting the group of the clicked rectangle and raising it (that is, moving it down in the DOM tree), so that group will be on top of all others. According to the API, raise():
Re-inserts each selected element, in order, as the last child of its parent. (emphasis mine)
"Moving down", "be on top" and "be the last child" may be a bit confusing and seem contradictory, but here is the explanation. Given this SVG structure:
<svg>
<foo></foo>
<bar></bar>
<baz></baz>
</svg>
<baz>, being the last element, is the one painted last, and it is the element visually on the top in the SVG. So, raising an element means moving it down in the SVG tree structure, but moving it up visually speaking.
Here is your updated fiddle: https://jsfiddle.net/86Lgaupt/
PS: I increased the stroke-width just to make visibly clear that the clicked rectangle is now on top.
Tag:
<div id='stacked-bar'></div>
Script:
var initStackedBarChart = {
draw: function(config) {
me = this,
domEle = config.element,
stackKey = config.key,
data = config.data,
margin = {top: 20, right: 20, bottom: 30, left: 50},
parseDate = d3.timeParse("%m/%Y"),
width = 550 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom,
xScale = d3.scaleBand().range([0, width]).padding(0.1),
yScale = d3.scaleLinear().range([height, 0]),
color = d3.scaleOrdinal(d3.schemeCategory20),
xAxis = d3.axisBottom(xScale).tickFormat(d3.timeFormat("%b")),
yAxis = d3.axisLeft(yScale),
svg = d3.select("#"+domEle).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top+10 + margin.bottom+10)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var stack = d3.stack()
.keys(stackKey)
.order(d3.stackOrderNone)
.offset(d3.stackOffsetNone);
var layers= stack(data);
data.sort(function(a, b) { return b.total - a.total; });
xScale.domain(data.map(function(d) { return parseDate(d.date); }));
yScale.domain([0, d3.max(layers[layers.length - 1], function(d) { return d[0] + d[1]; }) ]).nice();
var layer = svg.selectAll(".layer")
.data(layers)
.enter().append("g")
.attr("class", "layer")
.style("fill", function(d, i) { return color(i); });
layer.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr('class', 'bar')
.attr("x", function(d) { return xScale(parseDate(d.data.date)); })
.attr("y", function(d) { return yScale(d[1]); })
.attr("height", function(d) { return yScale(d[0]) - yScale(d[1]) -1; })
.attr("width", xScale.bandwidth())
.on('click', function(d, i) {
d3.selectAll('.bar').classed('selected', false);
d3.select(this).classed('selected', true);
});
svg.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + (height+5) + ")")
.call(xAxis);
svg.append("g")
.attr("class", "axis axis--y")
.attr("transform", "translate(0,0)")
.call(yAxis);
}
}
var data = [
{"date":"4/1854","total":45,"disease":12,"wounds":14,"other":25},
{"date":"5/1854","total":23,"disease":12,"wounds":0,"other":9},
{"date":"6/1854","total":38,"disease":11,"wounds":0,"other":6},
{"date":"7/1854","total":26,"disease":11,"wounds":8,"other":7}
];
var key = ["wounds", "other", "disease"];
initStackedBarChart.draw({
data: data,
key: key,
element: 'stacked-bar'
});
Css:
.axis text {
font: 10px sans-serif;
}
.axis line,
.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.axis--x path {
display: none;
}
.path-line {
fill: none;
stroke: yellow;
stroke-width: 1.5px;
}
svg {
background: #f0f0f0;
}
.selected{
stroke:#333;
stroke-width:2;
}

Dynamically scale data in an interactive chart, in which the data gets altered?

I have made an interactive bar chart, where the bars can be dragged up and down to adjust the data.
As the bar is dragged beyond the current max/min of the y-axis domain, the y-axis scales accordingly. However, I cannot get the rest of the bars to scale accordingly (i.e: if I increase one bar's value to a new extreme, the other bars should shrink along with the new scale)
I have a JS Fiddle here with everything that works so far.
// canvas properties
var margin =
{
top: 40,
bottom: 40,
right: 30,
left: 50
}
var w = 960 - margin.left - margin.right,
h = 500 - margin.top - margin.bottom;
// initiating axes
var x = d3.scale.ordinal()
.rangeRoundBands([0, w], 0.1);
var y = d3.scale.linear()
.range([h, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(0)
.tickPadding(6);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var zeroline = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(0)
.tickFormat('')
var svg = d3.select("body").append("svg")
.attr("width", w + margin.left + margin.right)
.attr("height", h + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var newValue;
var data = [
{name: "A", value: -15},
{name: "B", value: -20},
{name: "C", value: -22},
{name: "D", value: -18},
{name: "E", value: 2},
{name: "F", value: 6},
{name: "G", value: 26},
{name: "H", value: 18}
];
function type(d)
{
d.value = +d.value;
return d;
}
function generateChart(error, data)
{
/* ========== Parse Data & Create Axes ========== */
// create a new property called y (needed for d3.events)
var data = data.map(function (d, i)
{
return {
name: d.name,
value: d.value,
y: d.value
}
});
var max = d3.max(data, function (d) { return d.y; });
var min = -max;
y.domain([min, max]).nice();
x.domain(data.map(function (d) { return d.name; }));
var zz = svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (h / 2) + ")")
.call(zeroline);
var xx = svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (h + 20) + ")")
.call(xAxis);
var yy = svg.append("g")
.attr("class", "y axis")
.call(yAxis);
/* ========== Drag Behaviour for Rectangles ========== */
var drag = d3.behavior.drag()
.on("drag", resize);
/* ========== Create Rectangles ========== */
var DataBar = svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", function (d) { return "bar bar--" + (d.value < 0 ? "negative" : "positive"); })
.attr("id", function (d) { return (d.value < 0 ? "negative" : "positive"); })
.attr("x", function (d) { return x(d.name); })
.attr("y", function (d) { return y(Math.max(0, d.value)); })
.attr("width", x.rangeBand())
.attr("height", function (d) { return Math.abs(y(d.value) - y(0)); })
.attr("cursor", "ns-resize")
.call(drag);
/* ========== Drag Functions ========== */
function resize(d)
{
if (d3.select(this)[0][0].id == 'positive')
{
d.y = d3.event.y;
if (y.invert(d.y) >= 0) // positive -> postive
{
var barHeight = -(d.y - y(0));
var bar = d3.select(this);
bar.attr("y", function (d) { return d.y; })
.attr("height", barHeight)
.style("fill", "steelblue");
}
else if (y.invert(d.y) < 0) // positive -> negative
{
var barHeight = Math.abs((d.y) - y(0))
var dragy = d3.event.y
barHeight += dragy - (d.y);
var bar = d3.select(this)
bar.attr("height", barHeight)
.attr("y", y(0))
.style("fill", "darkorange");
}
newValue = y.invert(d.y);
}
else if (d3.select(this)[0][0].id == 'negative')
{
var barHeight = Math.abs(y(d.y) - y(0))
var dragy = d3.event.y
if (y.invert(dragy) < 0) // negative -> negative
{
barHeight += dragy - y(d.y);
var bar = d3.select(this)
bar.attr("height", barHeight)
.attr("y", y(0))
.style("fill", "darkorange");
}
else if (y.invert(dragy) >= 0) // negative -> positive
{
var barHeight = -(dragy - y(0));
var bar = d3.select(this);
bar.attr("y", function (d) { return dragy; })
.attr("height", barHeight)
.style("fill", "steelblue");
}
//newValue = y.invert(dragy);
}
var max = d3.max(data, function (d) { return d.value; });
var min = -max;
var update = [];
if (newValue > max)// || newValue < min)
{
y.domain([-newValue, newValue]).nice();
yy.call(yAxis)
}
}
}
generateChart('error!', data)
(Quick note: the y-axis rescaling only works with the initial blue bars at the moment.)
Add the following block of code after the if (newValue > max) { ... } block:
var selectedObjectName = d3.select(this).data()[0].name;
svg.selectAll("rect.bar").filter(function (d){
return (d.name != selectedObjectName);})
.attr("height", function (d) { return Math.abs(y(d.value) - y(0));})
.attr("y", function (d) { return y(Math.max(0, d.value)); });
The idea is to select all the rectangles, filter out the currently selected one, and re-adjust the height and y coordinate of the remaining rectangles. Fiddle

D3js exit() and update working, can't enter()

I have a scatter plot with D3 and I'm trying to add circles to a selection based on changing data. I'm passing the data selection down to two functions: render and update. The render function is the initial render and update has the enter() and exit() methods. I can easily add the initial data set and get the circles no longer in the data set to exit. I'm using d.id as the d3 placeholder.
The problem: when I try to enter() the added data points, nothing happens. I've checked the length of the new data selection, and it's larger than the pre-existing. On the DOM, the smaller data set remains (the circles that were already there), but no new circles enter, even though the data set has changed.
I've looked through lots of tutorials regarding data joins, and I think I've appropriately called my enter() and exit() methods. What gives?
Here is my code:
var container = angular.element(document.querySelector('.chart-container'))[0];
var margin = {
top: container.clientHeight / 12,
right: container.clientWidth / 14,
bottom: container.clientHeight / 10,
left: container.clientWidth / 11
};
var w = container.clientWidth - margin.left - margin.right;
var h = container.clientHeight - margin.top - margin.bottom;
// ******** **************** ******** //
// ******** INITIAL RENDER ******** //
function render(input) {
console.log(Object.keys(input).length);
var xScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ctc"]; })])
.range([0, w])
.nice();
var yScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ttc"]; })])
.range([h, 0])
.nice();
var rScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["effective"]; })])
.range([2, 15]);
// *********** //
// SVG ELEMENT //
var svg = d3.select('.chart-container')
.append('svg')
.attr('class', 'scatter')
.attr('viewBox', '0, 0, ' + Math.round(w + margin.left + margin.right) + ', ' + Math.round(h + margin.top + margin.bottom))
.attr('preserveAspectRatio', 'xMinYMin')
// used to center element and make use of margins
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// add circles in group
var circles = svg.append('g')
.attr('class','circles')
.attr('clip-path','url(#chart-area)');
// add individual circles
var circle = circles.selectAll('circle')
.data(input, function(d) {return d.id;})
.enter()
.append('circle')
.attr('class', 'circle')
.attr('cx', function(d) { return xScale(d["ctc"]); })
.attr('cy', function(d) { return yScale(d["ttc"]); })
.attr('r', function(d) { return rScale(d["effective"]); })
.attr('fill', function(d, i) { return d["effective"]; })
.on('mouseover', function(d) {
tooltip.style('visibility', 'visible');
return tooltip.text(d["technology"]);
})
.on("mousemove", function(){ return tooltip.style("top",
(d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");})
// append clip path
svg.append('clipPath')
.attr('id','chart-area')
.append('rect')
.attr('class', 'rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', w)
.attr('height', h);
};
// ******** **************** ******** //
// ******** UPDATE ******** //
function update(updateObject) {
var input = updateObject;
var xScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ctc"]; })])
.range([0, w])
.nice();
var yScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ttc"]; })])
.range([h, 0])
.nice();
var rScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["effective"]; })])
.range([2, 15]);
var svg = d3.select('svg')
.data(input)
.attr('viewBox', '0, 0, ' + Math.round(w + margin.left + margin.right) + ', ' + Math.round(h + margin.top + margin.bottom))
.attr('preserveAspectRatio', 'xMinYMin')
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// BIND TO DATA
var circles = d3.selectAll('circle')
.data(input, function(d) { return d.id; });
// Circles Enter
circles.enter()
.insert('svg:circle')
.attr('class', 'circle')
.attr('cx', function(d) { return xScale(d["ctc"]); })
.attr('cy', function(d) { return yScale(d["ttc"]); })
.attr('r', function(d) { return rScale(d["effective"]); });
/*
.on('mouseover', function(d) {
tooltip.style('visibility', 'visible');
return tooltip.text(d["technology"]);
})
.on("mousemove", function(){ return tooltip.style("top",
(d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");})
*/
// UPDATE
circles.transition()
.duration(1000)
.attr('cx', function(d) { return xScale(d["ctc"]); })
.attr('cy', function(d) { return yScale(d["ttc"]); })
.attr('r', function(d) { return rScale(d["effective"]); });
// EXIT
circles.exit()
.transition()
.duration(500)
.attr('r', 0)
.style('opacity', 0)
.style('fill', 'gray')
.remove();
}
Update
here is a codepen for testing: http://codepen.io/himmel/pen/JdNJMM
The problem with the code is, that you are trying to use an object as data. d3.selection.data() takes an array, not an object. See the d3 wiki for more information on the data() function.
I have created an updated version of your codepen. I changed the data to an array and applied the correct conventional margin. Moreover I simplified the code by removing the double initialization of scales and the svg element.

Display Pie chart, Grouped and Stacked bar chart in one page

I want to display two charts in one page.The Pie chart gets displayed but the Grouped and Stacked bar chart is not displaying . I tried to change the Id name in but no luck :( . Will appreciate if anyone helps me with the code correction .
/* Display Matrix Chart ,Pie chart, Grouped and Stacked bar chart in one page */
<apex:page showHeader="false">
<apex:includeScript value="{!URLFOR($Resource.jquery1)}"/>
<apex:includeScript value="{!URLFOR($Resource.D3)}"/>
<apex:includeScript value="{!URLFOR($Resource.nvD3)}"/>
<div id="body" height="50%" width="100px" ></div> // Id for Pie chart
<div id="body1" height="30%" width="90px"></div> // Id for Stacked and Grouped bar chart
<script>
// Matrix Chart starts here
var drawChart = function(divId,matrixReportId) {
$.ajax('/services/data/v29.0/analytics/reports/'+matrixReportId,
{
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer {!$Api.Session_ID}');
},
success: function(response) {
console.log(response);
var chart = nv.models.multiBarChart();
var chartData = [];
document.getElementById(divId).innerHTML = '';
$.each(response.groupingsDown.groupings, function(di, de) {
var values = [];
chartData.push({"key":de.label, "values": values});
$.each(response.groupingsAcross.groupings, function(ai, ae) {
values.push({"x": ae.label, "y": response.factMap[de.key+"!"+ae.key].aggregates[0].value});
});
});
d3.select('#'+divId).datum(chartData).transition().duration(100).call(chart);
window.setTimeout(function(){
drawChart(divId,matrixReportId);
}, 5000);
}
}
);
};
$(document).ready(function(){
drawChart('chart','00O90000005SSHv');
});
// Pie Chart Starts here
var width =250 ,
height = 450,
radius = Math.min(width, height) / 2;
var data = [{"age":"<5","population":2704659},{"age":"14-17","population":2159981},
{"age":"14-17","population":2159981},{"age":"18-24","population":3853788},
{"age":"25-44","population":14106543},{"age":"45-64","population":8819342},
{"age":">65","population":612463}];
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc().outerRadius(radius - 10).innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
var svg = d3.select("#body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.age); });
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; });
// Grouped and Stacked Bar Chart starts here
var n = 2, // number of layers
m = 10, // number of samples per layer
stack = d3.layout.stack(),
layers = stack(d3.range(n).map(function() { return bumpLayer(m, .1); })),
yGroupMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y; }); }),
yStackMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); });
var margin = {top: 40, right: 10, bottom: 20, left: 10},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.domain(d3.range(m))
.rangeRoundBands([0, width], .08);
var y = d3.scale.linear()
.domain([0, yStackMax])
.range([height, 0]);
var color = d3.scale.linear()
.domain([0, n - 1])
.range(["#aad", "#556"]);
var xAxis = d3.svg.axis()
.scale(x)
.tickSize(0)
.tickPadding(6)
.orient("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 + ")");
var layer = svg.selectAll(".layer")
.data(layers)
.enter().append("g")
.attr("class", "layer")
.style("fill", function(d, i) { return color(i); });
var rect = layer.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("x", function(d) { return x(d.x); })
.attr("y", height)
.attr("width", x.rangeBand())
.attr("height", 0);
rect.transition()
.delay(function(d, i) { return i * 10; })
.attr("y", function(d) { return y(d.y0 + d.y); })
.attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
d3.selectAll("input").on("change", change);
var timeout = setTimeout(function() {
d3.select("input[value=\"grouped\"]").property("checked", true).each(change);
}, 2000);
function change() {
clearTimeout(timeout);
if (this.value === "grouped") transitionGrouped();
else transitionStacked();
}
function transitionGrouped() {
y.domain([0, yGroupMax]);
rect.transition()
.duration(500)
.delay(function(d, i) { return i * 10; })
.attr("x", function(d, i, j) { return x(d.x) + x.rangeBand() / n * j; })
.attr("width", x.rangeBand() / n)
.transition()
.attr("y", function(d) { return y(d.y); })
.attr("height", function(d) { return height - y(d.y); });
}
function transitionStacked() {
y.domain([0, yStackMax]);
rect.transition()
.duration(500)
.delay(function(d, i) { return i * 10; })
.attr("y", function(d) { return y(d.y0 + d.y); })
.attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); })
.transition()
.attr("x", function(d) { return x(d.x); })
.attr("width", x.rangeBand());
}
// Inspired by Lee Byron's test data generator.
function bumpLayer(n, o) {
function bump(a) {
var x = 1/(.1 + Math.random()),
y = 2*Math.random()-.5,
z = 10/(.1 + Math.random());
for (var i = 0; i < n; i++) {
var w = (i/n- y) * z;
a[i] += x * Math.exp(-w * w);
}
}
var a=[],i;
for (i = 0; i < n; ++i) a[i] = o + o * Math.random();
for (i = 0; i < 5; ++i) bump(a);
return a.map(function(d, i) { return {x: i, y: Math.max(0, d)}; });
}
</script>
<svg id="chart" height="50%" width="500px" ></svg> // Id for Matrix chart
</apex:page>
Thanks in advance
first, as we discussed here (d3 Donut chart does not render), you should position your
<div id="body1" height="30%" width="90px"></div>
above the script.
second, you are missing the # in your second svg-declaration to correctly select the div by its id, it has to be
var svg = d3.select("#body1").append("svg")
you could also think about naming the second svg differently (eg svg2) so you don't override your first svg-variable (in case you want to do something with it later).

Categories

Resources