Making data points transition smoothly? - javascript

I am trying to make a time series move smoothly like my x-axis. Essentially, I continuously update an array of fixed length with a new random measurement (i.e. add one, delete one) each 200 milliseconds. Here is my original code:
////////////////////////////////////////////////////////////
////////////////////// Set-up /////////////////////////////
////////////////////////////////////////////////////////////
const margin = {
left: 80,
right: 80,
top: 30,
bottom: 165
};
//Actual graph smaller than svg container
var width = $('#chart').width() - margin.left - margin.right;
var height = $('#chart').height() - margin.top - margin.bottom;
const yDomain = [0, 70];
const yTickValues = [0, 10, 20, 30, 40, 50, 60, 70];
const TIME_INTERVAL = 200;
//xAxis domain-> 10 seconds
const originalTime1 = "1970-01-01T00:00:00",
originalTime2 = "1970-01-01T00:00:10";
//Get the milliseconds since UNIX epoch
var date1 = new Date(originalTime1).getTime(),
date2 = new Date(originalTime2).getTime();
//Random measurements
var measurements = [];
//Equally spaced time measurements within millisecond interval
var arraySize = Math.floor(Math.abs(date2 - date1) / TIME_INTERVAL);
//Random measurements
var trueValue = 25;
var accuracyValue = 45;
var precisionValue = 25;
////////////////////////////////////////////////////////////
///////////////////////// SVG //////////////////////////////
////////////////////////////////////////////////////////////
const svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
const g = svg.append("g")
.attr("transform", "translate(" + margin.left + ", " + margin.top + ")");
////////////////////////////////////////////////////////////
///////////////////// Axes & Scales ////////////////////////
////////////////////////////////////////////////////////////
var xAxisGroup = g.append("g")
.attr("class", "x-axis");
var yAxisGroup = g.append("g")
.attr("class", "y-axis");
//Dynamic
var xScale = d3.scaleTime();
//Fixed
var yScale = d3.scaleLinear()
.domain([yDomain[0], yDomain[1]])
.range([height - margin.bottom, 0]);
const xAxis = d3.axisBottom(xScale)
.ticks(d3.timeSecond.every(1))
.tickSizeInner(15)
.tickFormat(d3.timeFormat("%M:%S"));
const yAxis = d3.axisLeft()
.scale(yScale)
.tickValues(yTickValues)
.tickFormat(d3.format(".0f"));
////////////////////////////////////////////////////////////
/////////////////////// Functions //////////////////////////
////////////////////////////////////////////////////////////
function draw() {
//Transition parameters
t = d3.transition()
.duration(TIME_INTERVAL)
.ease(d3.easeLinear);
//Update xAxis scale
xScale.domain([date1, date2])
.range([0, width]);
//Call axes
xAxisGroup.attr("transform", "translate(0," + (height - margin.bottom) + ")")
.transition(t)
.call(xAxis);
yAxisGroup.call(yAxis);
//DATA JOIN
var circles = g.selectAll("circle").data(measurements);
//EXIT
circles.exit().remove();
//UPDATE
//Update DOM elements on the screen with smooth linear transition
circles
.attr("cx", function(d) {
return xScale(d[0]);
})
.attr("cy", function(d) {
return yScale(d[1]);
});
//ENTER
circles.enter()
.append("circle")
.attr("class", "enter")
.attr("fill", "black")
.attr("r", "4")
.attr("cx", function(d) {
return xScale(d[0]);
})
.attr("cy", function(d) {
return yScale(d[1]);
});
//Update dates & random array for next iteration
date1 += TIME_INTERVAL;
date2 += TIME_INTERVAL;
measurements.push(addNewMeasurement());
measurements.shift();
};
function initializeRandomArray() {
for (i = 1; i <= arraySize; i++) {
var temp = [];
temp[0] = date1;
//Math.random not exactly 1 -> but VERY CLOSE
var precision = (Math.random() * 2 * precisionValue) - precisionValue;
temp[1] = accuracyValue + precision;
//Add new element at the end of the array
measurements.push(temp);
date1 += TIME_INTERVAL;
}
//Reset back date1
date1 = new Date(originalTime1).getTime();
};
function addNewMeasurement() {
var temp = [];
temp[0] = date2;
var precision = (Math.random() * 2 * precisionValue) - precisionValue;
temp[1] = accuracyValue + precision;
return temp;
};
////////////////////////////////////////////////////////////
///////////////////////// Main /////////////////////////////
////////////////////////////////////////////////////////////
initializeRandomArray();
draw();
d3.interval(function() {
draw();
}, TIME_INTERVAL);
.x-axis,
.y-axis {
font-size: 0.8em;
stroke-width: 0.06em;
}
#chart {
width: 600px;
height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart"></div>
The problem is when I apply the transition t to my data points, I get:
////////////////////////////////////////////////////////////
////////////////////// Set-up /////////////////////////////
////////////////////////////////////////////////////////////
const margin = {
left: 80,
right: 80,
top: 30,
bottom: 165
};
//Actual graph smaller than svg container
var width = $('#chart').width() - margin.left - margin.right;
var height = $('#chart').height() - margin.top - margin.bottom;
const yDomain = [0, 70];
const yTickValues = [0, 10, 20, 30, 40, 50, 60, 70];
const TIME_INTERVAL = 200;
//xAxis domain-> 10 seconds
const originalTime1 = "1970-01-01T00:00:00",
originalTime2 = "1970-01-01T00:00:10";
//Get the milliseconds since UNIX epoch
var date1 = new Date(originalTime1).getTime(),
date2 = new Date(originalTime2).getTime();
//Random measurements
var measurements = [];
//Equally spaced time measurements within millisecond interval
var arraySize = Math.floor(Math.abs(date2 - date1) / TIME_INTERVAL);
//Random measurements
var trueValue = 25;
var accuracyValue = 45;
var precisionValue = 25;
////////////////////////////////////////////////////////////
///////////////////////// SVG //////////////////////////////
////////////////////////////////////////////////////////////
const svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
const g = svg.append("g")
.attr("transform", "translate(" + margin.left + ", " + margin.top + ")");
////////////////////////////////////////////////////////////
///////////////////// Axes & Scales ////////////////////////
////////////////////////////////////////////////////////////
var xAxisGroup = g.append("g")
.attr("class", "x-axis");
var yAxisGroup = g.append("g")
.attr("class", "y-axis");
//Dynamic
var xScale = d3.scaleTime();
//Fixed
var yScale = d3.scaleLinear()
.domain([yDomain[0], yDomain[1]])
.range([height - margin.bottom, 0]);
const xAxis = d3.axisBottom(xScale)
.ticks(d3.timeSecond.every(1))
.tickSizeInner(15)
.tickFormat(d3.timeFormat("%M:%S"));
const yAxis = d3.axisLeft()
.scale(yScale)
.tickValues(yTickValues)
.tickFormat(d3.format(".0f"));
////////////////////////////////////////////////////////////
/////////////////////// Functions //////////////////////////
////////////////////////////////////////////////////////////
function draw() {
//Transition parameters
t = d3.transition()
.duration(TIME_INTERVAL)
.ease(d3.easeLinear);
//Update xAxis scale
xScale.domain([date1, date2])
.range([0, width]);
//Call axes
xAxisGroup.attr("transform", "translate(0," + (height - margin.bottom) + ")")
.transition(t)
.call(xAxis);
yAxisGroup.call(yAxis);
//DATA JOIN
var circles = g.selectAll("circle").data(measurements);
//EXIT
circles.exit().remove();
//UPDATE
circles
.transition(t)
.attr("cx", function(d) {
return xScale(d[0]);
})
.attr("cy", function(d) {
return yScale(d[1]);
});
//ENTER
circles.enter()
.append("circle")
.attr("class", "enter")
.attr("fill", "black")
.attr("r", "4")
.attr("cx", function(d) {
return xScale(d[0]);
})
.attr("cy", function(d) {
return yScale(d[1]);
});
//Update dates & random array for next iteration
date1 += TIME_INTERVAL;
date2 += TIME_INTERVAL;
measurements.push(addNewMeasurement());
measurements.shift();
};
function initializeRandomArray() {
for (i = 1; i <= arraySize; i++) {
var temp = [];
temp[0] = date1;
//Math.random not exactly 1 -> but VERY CLOSE
var precision = (Math.random() * 2 * precisionValue) - precisionValue;
temp[1] = accuracyValue + precision;
//Add new element at the end of the array
measurements.push(temp);
date1 += TIME_INTERVAL;
}
//Reset back date1
date1 = new Date(originalTime1).getTime();
};
function addNewMeasurement() {
var temp = [];
temp[0] = date2;
var precision = (Math.random() * 2 * precisionValue) - precisionValue;
temp[1] = accuracyValue + precision;
return temp;
};
////////////////////////////////////////////////////////////
///////////////////////// Main /////////////////////////////
////////////////////////////////////////////////////////////
initializeRandomArray();
draw();
d3.interval(function() {
draw();
}, TIME_INTERVAL);
.x-axis,
.y-axis {
font-size: 0.8em;
stroke-width: 0.06em;
}
#chart {
width: 600px;
height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart"></div>
Is there a simple way of making the data points move horizontally smoothly? Thank you very much for your input!

Related

Slight lag in translation animation using D3.interval()

I have created a time series animation. Essentially, I generate a random datum every 20ms and the time axis slides continuously leftwards on a one second interval. D3.interval() creates what I want, but the graph seems "choppy". I assume it has something to do with the web browser or D3? Here is my code (expand the snippet window for a better view):
////////////////////////////////////////////////////////////
////////////////////// Set-up /////////////////////////////
////////////////////////////////////////////////////////////
const margin = { left: 80, right: 80, top: 30, bottom: 165},
TIME_MEASUREMENT = 20,
TIME_INTERVAL = 1000,
TIME_FRAME = 10000;
let width = $("#chart").width() - margin.left - margin.right,
height = $("#chart").height() - margin.top - margin.bottom;
let date1 = 0,
date2 = TIME_FRAME;
let accuracy = 20,
precision = 20,
aF = 2, //accuracyFactor
pF = 1; //precisionFactor
let random = d3.randomUniform(-(pF * precision), pF * precision),
count = TIME_FRAME/TIME_MEASUREMENT + 1;
let data = d3.range(count).map((d,i) => random() + accuracy );
const yDomain = [0, 50],
yTickValues = [0, 10, 20, 30, 40, 50];
////////////////////////////////////////////////////////////
///////////////////////// SVG //////////////////////////////
////////////////////////////////////////////////////////////
const svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
const g = svg.append("g")
.attr("transform", "translate(" + margin.left + ", " + margin.top + ")");
////////////////////////////////////////////////////////////
///////////////////// Axes & Scales ////////////////////////
////////////////////////////////////////////////////////////
//X axis - dynamic
let xAxisGroup = g.append("g")
.attr("class", "x-axis")
.attr("transform", "translate(0," + (height) + ")");
let xScale = d3.scaleTime();
const xAxis = d3.axisBottom(xScale)
.ticks(d3.timeSecond.every(1))
.tickSizeInner(15)
.tickFormat(d3.timeFormat("%M:%S"));
//Y axis - static
let yAxisGroup = g.append("g")
.attr("class", "y-axis");
let yScale = d3.scaleLinear()
.domain(yDomain)
.range([height, 0]);
const yAxis = d3.axisLeft()
.scale(yScale)
.tickValues(yTickValues)
.tickFormat(d3.format(".0f"));
yAxisGroup.call(yAxis);
//Data points - static
let dataScale = d3.scaleTime()
.domain([date1,date2])
.range([0,width]);
////////////////////////////////////////////////////////////
/////////////////////// Functions //////////////////////////
////////////////////////////////////////////////////////////
function drawData(){
xScale.domain([date1, date2])
.range([0, width]);
xAxisGroup
.transition()
.duration(TIME_MEASUREMENT)
.ease(d3.easeLinear)
.call(xAxis);
g.selectAll("circle")
.data(data)
.join(
function(enter){
enter.append("circle")
.attr("cx", (d,i) => dataScale(i*TIME_MEASUREMENT))
.attr("cy", (d,i) => yScale(d))
.attr("fill", "black")
.attr("r","3");
},
function(update){
update
.attr("cx", (d,i) => dataScale(i*TIME_MEASUREMENT))
.attr("cy", (d,i) => yScale(d))
.transition()
.ease(d3.easeLinear)
.attr("transform", "translate(" + dataScale(-TIME_MEASUREMENT) + ", 0)");
}
);
data.push(random() + accuracy);
data.shift();
date1 += TIME_INTERVAL/50;
date2 += TIME_INTERVAL/50;
};
////////////////////////////////////////////////////////////
///////////////////////// Main /////////////////////////////
////////////////////////////////////////////////////////////
d3.interval(drawData, TIME_MEASUREMENT);
x-axis,
.y-axis {
font-size: 0.8em;
stroke-width: 0.06em;
}
#chart {
width: 600px;
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="//d3js.org/d3.v6.min.js"></script>
<div id="chart"></div>
I don't get this "choppy effect" when I use d3.timer or setInterval, but each second slides as if it were ~850ms. Thank you for your input!

D3.js jumpy zoom behaviour

I am trying to do a zoomable heatmap and the community here on SO have helped massively, however I am now stuck the whole day today trying to fix a glitch and I am hitting the wall every single time.
The issue is that the zoom looks jumpy, ie the plot is rendered fine, however when the zoom event is triggered some kind of transformation happens that changes the axes and the scaling in an abrupt way. The code below demonstrates this issue. The problem does not always happen, it depends on the heatmap dimension and/or the number of the dots.
Some similar cases from people with the same problem here on SO turned out to be that the zoom was not applied to the correct object but I think I am not doing that mistake. Many thanks in advance
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000000;
}
.x.axis path {
//display: none;
}
.chart rect {
fill: steelblue;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
#tooltip {
position: absolute;
background-color: #2B292E;
color: white;
font-family: sans-serif;
font-size: 15px;
pointer-events: none;
/*dont trigger events on the tooltip*/
padding: 15px 20px 10px 20px;
text-align: center;
opacity: 0;
border-radius: 4px;
}
</style>
<title>Heatmap Chart</title>
<!-- Reference style.css -->
<!-- <link rel="stylesheet" type="text/css" href="style.css">-->
<!-- Reference minified version of D3 -->
<script src='https://d3js.org/d3.v4.min.js' type='text/javascript'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='heatmap.js' type='text/javascript'></script>
</head>
<body>
<div id="chart">
<svg width="550" height="1000"></svg>
</div>
<script>
var dataset = [];
for (let i = 1; i < 60; i++) { //360
for (j = 1; j < 70; j++) { //75
dataset.push({
xKey: i,
xLabel: "xMark " + i,
yKey: j,
yLabel: "yMark " + j,
val: Math.random() * 25,
})
}
};
var svg = d3.select("#chart")
.select("svg")
var xLabels = [],
yLabels = [];
for (i = 0; i < dataset.length; i++) {
if (i == 0) {
xLabels.push(dataset[i].xLabel);
var j = 0;
while (dataset[j + 1].xLabel == dataset[j].xLabel) {
yLabels.push(dataset[j].yLabel);
j++;
}
yLabels.push(dataset[j].yLabel);
} else {
if (dataset[i - 1].xLabel == dataset[i].xLabel) {
//do nothing
} else {
xLabels.push(dataset[i].xLabel);
}
}
};
var margin = {
top: 0,
right: 25,
bottom: 40,
left: 75
};
var width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var dotSpacing = 0,
dotWidth = width / (2 * (xLabels.length + 1)),
dotHeight = height / (2 * yLabels.length);
// var dotWidth = 1,
// dotHeight = 3,
// dotSpacing = 0.5;
var daysRange = d3.extent(dataset, function(d) {
return d.xKey
}),
days = daysRange[1] - daysRange[0];
var hoursRange = d3.extent(dataset, function(d) {
return d.yKey
}),
hours = hoursRange[1] - hoursRange[0];
var tRange = d3.extent(dataset, function(d) {
return d.val
}),
tMin = tRange[0],
tMax = tRange[1];
// var width = (dotWidth * 2 + dotSpacing) * days,
// height = (dotHeight * 2 + dotSpacing) * hours;
// var width = +svg.attr("width") - margin.left - margin.right,
// height = +svg.attr("height") - margin.top - margin.bottom;
var colors = ['#2C7BB6', '#00A6CA', '#00CCBC', '#90EB9D', '#FFFF8C', '#F9D057', '#F29E2E', '#E76818', '#D7191C'];
// the scale
var scale = {
x: d3.scaleLinear()
.domain([-1, d3.max(dataset, d => d.xKey)])
.range([-1, width]),
y: d3.scaleLinear()
.domain([0, d3.max(dataset, d => d.yKey)])
.range([height, 0]),
//.range([(dotHeight * 2 + dotSpacing) * hours, dotHeight * 2 + dotSpacing]),
};
var xBand = d3.scaleBand().domain(xLabels).range([0, width]),
yBand = d3.scaleBand().domain(yLabels).range([height, 0]);
var axis = {
x: d3.axisBottom(scale.x).tickFormat((d, e) => xLabels[d]),
y: d3.axisLeft(scale.y).tickFormat((d, e) => yLabels[d]),
};
function updateScales(data) {
scale.x.domain([-1, d3.max(data, d => d.xKey)]),
scale.y.domain([0, d3.max(data, d => d.yKey)])
}
var colorScale = d3.scaleQuantile()
.domain([0, colors.length - 1, d3.max(dataset, function(d) {
return d.val;
})])
.range(colors);
var zoom = d3.zoom()
.scaleExtent([dotWidth, dotHeight])
.on("zoom", zoomed);
var tooltip = d3.select("body").append("div")
.attr("id", "tooltip")
.style("opacity", 0);
// SVG canvas
svg = d3.select("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
//.call(zoom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Clip path
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height + dotHeight);
// Heatmap dots
var heatDotsGroup = svg.append("g")
.attr("clip-path", "url(#clip)")
.append("g");
heatDotsGroup.call(zoom);
//Create X axis
var renderXAxis = svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + scale.y(-1) + ")")
.call(axis.x)
//Create Y axis
var renderYAxis = svg.append("g")
.attr("class", "y axis")
.call(axis.y);
function zoomed() {
d3.event.transform.y = 0;
d3.event.transform.x = Math.min(d3.event.transform.x, 5);
d3.event.transform.x = Math.max(d3.event.transform.x, (1 - d3.event.transform.k) * width);
d3.event.transform.k = Math.max(d3.event.transform.k, 1);
//console.log(d3.event.transform)
// update: rescale x axis
renderXAxis.call(axis.x.scale(d3.event.transform.rescaleX(scale.x)));
heatDotsGroup.attr("transform", d3.event.transform.toString().replace(/scale\((.*?)\)/, "scale($1, 1)"));
}
svg.call(renderPlot, dataset)
function renderPlot(selection, dataset) {
//updateScales(dataset);
heatDotsGroup.selectAll("ellipse")
.data(dataset)
.enter()
.append("ellipse")
.attr("cx", function(d) {
return scale.x(d.xKey) - xBand.bandwidth();
})
.attr("cy", function(d) {
return scale.y(d.yKey) + yBand.bandwidth();
})
.attr("rx", dotWidth)
.attr("ry", dotHeight)
.attr("fill", function(d) {
return colorScale(d.val);
})
.on("mouseover", function(d) {
$("#tooltip").html("X: " + d.xKey + "<br/>Y: " + d.yKey + "<br/>Value: " + Math.round(d.val * 100) / 100);
var xpos = d3.event.pageX + 10;
var ypos = d3.event.pageY + 20;
$("#tooltip").css("left", xpos + "px").css("top", ypos + "px").animate().css("opacity", 1);
}).on("mouseout", function() {
$("#tooltip").animate({
duration: 500
}).css("opacity", 0);
});
}
</script>
</body>
</html>
Change the zoom scaleExtend
var zoom = d3.zoom()
.scaleExtent([1, dotHeight])
.on("zoom", zoomed);
Call the zoom on the whole svg not on the heatDotsGroup because this node receives the tranformation, and also not on the g node that has the graph transformation here variable svg (to keep things a bit obscure)
svg = d3.select("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.call(zoom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// heatDotsGroup.call(zoom);
Don't limit the zoom scale k in the tick. Already taken care of by the scaleExtent()
// d3.event.transform.k = Math.max(d3.event.transform.k, 1);
Why calculate all the d3.max() when you already have calculated the d3.extent() of these values?

d3.js: enter-update-exit pattern - Old points not removed

I am trying to do the enter-update-exit pattern on this graph below (which was built with the tremendous help of some very kind ppl here at SO but I am now stuck again unfortunately. I cant make the pattern work but I am certain I pick up the correct object (named heatDotsGroup in the code below).
I can however check in Chrome's developer tools that this object contains the nodes (ellipses) but the pattern doesn't work, therefore clearly I am doing something wrong.
Any ideas please? Many thanks!
function heatmap(dataset) {
var svg = d3.select("#chart")
.select("svg")
var xLabels = [],
yLabels = [];
for (i = 0; i < dataset.length; i++) {
if (i==0){
xLabels.push(dataset[i].xLabel);
var j = 0;
while (dataset[j+1].xLabel == dataset[j].xLabel){
yLabels.push(dataset[j].yLabel);
j++;
}
yLabels.push(dataset[j].yLabel);
} else {
if (dataset[i-1].xLabel == dataset[i].xLabel){
//do nothing
} else {
xLabels.push(dataset[i].xLabel);
}
}
};
var margin = {top: 0, right: 25,
bottom: 60, left: 75};
var width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var dotSpacing = 0,
dotWidth = width/(2*(xLabels.length+1)),
dotHeight = height/(2*yLabels.length);
var daysRange = d3.extent(dataset, function (d) {return d.xKey}),
days = daysRange[1] - daysRange[0];
var hoursRange = d3.extent(dataset, function (d) {return d.yKey}),
hours = hoursRange[1] - hoursRange[0];
var tRange = d3.extent(dataset, function (d) {return d.val}),
tMin = tRange[0],
tMax = tRange[1];
var colors = ['#2C7BB6', '#00A6CA', '#00CCBC', '#90EB9D', '#FFFF8C', '#F9D057', '#F29E2E', '#E76818', '#D7191C'];
// the scale
var scale = {
x: d3.scaleLinear()
.range([-1, width]),
y: d3.scaleLinear()
.range([height, 0]),
};
var xBand = d3.scaleBand().domain(xLabels).range([0, width]),
yBand = d3.scaleBand().domain(yLabels).range([height, 0]);
var axis = {
x: d3.axisBottom(scale.x).tickFormat((d, e) => xLabels[d]),
y: d3.axisLeft(scale.y).tickFormat((d, e) => yLabels[d]),
};
function updateScales(data){
scale.x.domain([0, d3.max(data, d => d.xKey)]),
scale.y.domain([ 0, d3.max(data, d => d.yKey)])
}
var colorScale = d3.scaleQuantile()
.domain([0, colors.length - 1, d3.max(dataset, function (d) {return d.val;})])
.range(colors);
var zoom = d3.zoom()
.scaleExtent([1, dotHeight])
.on("zoom", zoomed);
var tooltip = d3.select("body").append("div")
.attr("id", "tooltip")
.style("opacity", 0);
// SVG canvas
svg = d3.select("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.call(zoom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Clip path
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height+dotHeight);
// Heatmap dots
var heatDotsGroup = svg.append("g")
.attr("clip-path", "url(#clip)")
.append("g");
//Create X axis
var renderXAxis = svg.append("g")
.attr("class", "x axis")
//.attr("transform", "translate(0," + scale.y(-0.5) + ")")
//.call(axis.x)
//Create Y axis
var renderYAxis = svg.append("g")
.attr("class", "y axis")
.call(axis.y);
function zoomed() {
d3.event.transform.y = 0;
d3.event.transform.x = Math.min(d3.event.transform.x, 5);
d3.event.transform.x = Math.max(d3.event.transform.x, (1 - d3.event.transform.k) * width);
// console.log(d3.event.transform)
// update: rescale x axis
renderXAxis.call(axis.x.scale(d3.event.transform.rescaleX(scale.x)));
// Make sure that only the x axis is zoomed
heatDotsGroup.attr("transform", d3.event.transform.toString().replace(/scale\((.*?)\)/, "scale($1, 1)"));
}
svg.call(renderPlot, dataset)
function renderPlot(selection, dataset){
//Do the axes
updateScales(dataset)
selection.select('.y.axis').call(axis.y)
selection.select('.x.axis')
.attr("transform", "translate(0," + scale.y(-0.5) + ")")
.call(axis.x)
// Do the chart
const update = heatDotsGroup.selectAll("ellipse")
.data(dataset);
update
.enter()
.append("ellipse")
.attr("cx", function (d) {return scale.x(d.xKey) - xBand.bandwidth();})
.attr("cy", function (d) {return scale.y(d.yKey) + yBand.bandwidth();})
.attr("rx", dotWidth)
.attr("ry", dotHeight)
.attr("fill", function (d) {
return colorScale(d.val);}
)
.merge(update).transition().duration(800);
update.exit().remove();
}
};
#clickMe{
height:50px;
width:150px;
background-color:lavender;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Heatmap Chart</title>
<!-- Reference style.css -->
<!-- <link rel="stylesheet" type="text/css" href="style.css">-->
<!-- Reference minified version of D3 -->
<script src='https://d3js.org/d3.v4.min.js' type='text/javascript'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='heatmap_v4.js' type='text/javascript'></script>
</head>
<body>
<input id="clickMe" type="button" value="click me to push new data" onclick="run();" />
<div id='chart'>
<svg width="700" height="500">
<g class="focus">
<g class="xaxis"></g>
<g class="yaxis"></g>
</g>
</svg>
</div>
<script>
function run() {
var dataset = [];
for (let i = 1; i < 360; i++) { //360
for (j = 1; j < 7; j++) { //75
dataset.push({
xKey: i,
xLabel: "xMark " + i,
yKey: j,
yLabel: "yMark " + j,
val: Math.random() * 25,
})
}
};
heatmap(dataset)
}
$(document).ready(function() {});
</script>
</body>
</html>
The issue is that you are not using the same selection each time you run the enter/exit/update cycle. When the button is pushed you:
Generate new data
Run the heatmap function
The heatmap function selects the svg and appends a fresh g called heatDotsGroup
The update function is called and passed the newly created g as a selection
The enter cycle appends everything because the new g is empty.
As a result both the exit and udpate cycles are empty. Try:
console.log(update.size(),update.exit().size()) // *Without any merge*
You should see both are empty each update. This is because all elements are entered each time, which why each update increases the number of ellipses.
I've pulled out a bunch of variable declarations and append statements from the heatmap function, things that only need to be run once (I could go further, but I just did a minimum). I've also merged your update and enter selection prior to setting attributes (as we want to set the new attributes if we update).The below snippet should demonstrate this change.
In the snippet, on button push the following happens:
Generate new data
Run the heatmap function
The heatmap function selects existing selections and doesn't append anything new
The update function is called and passed the selection used by previous update/enter/exit cycles containing any existing nodes.
The update function enters/exits/updates elements as needed based on the existing nodes.
Here's a working version based on the above:
// Things to set/append once:
var svg = d3.select("#chart")
.select("svg")
var margin = {top: 0, right: 25,bottom: 60, left: 75};
var width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
svg = 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 clip = svg.append("clipPath")
.attr("id", "clip")
.append("rect")
var heatDotsGroup = svg.append("g")
.attr("clip-path", "url(#clip)")
.append("g");
var xAxis = svg.append("g").attr("class", "x axis");
var yAxis = svg.append("g").attr("class", "y axis")
function heatmap(dataset) {
var xLabels = [],
yLabels = [];
for (i = 0; i < dataset.length; i++) {
if (i==0){
xLabels.push(dataset[i].xLabel);
var j = 0;
while (dataset[j+1].xLabel == dataset[j].xLabel){
yLabels.push(dataset[j].yLabel);
j++;
}
yLabels.push(dataset[j].yLabel);
} else {
if (dataset[i-1].xLabel == dataset[i].xLabel){
//do nothing
} else {
xLabels.push(dataset[i].xLabel);
}
}
};
var dotSpacing = 0,
dotWidth = width/(2*(xLabels.length+1)),
dotHeight = height/(2*yLabels.length);
var daysRange = d3.extent(dataset, function (d) {return d.xKey}),
days = daysRange[1] - daysRange[0];
var hoursRange = d3.extent(dataset, function (d) {return d.yKey}),
hours = hoursRange[1] - hoursRange[0];
var tRange = d3.extent(dataset, function (d) {return d.val}),
tMin = tRange[0],
tMax = tRange[1];
var colors = ['#2C7BB6', '#00A6CA', '#00CCBC', '#90EB9D', '#FFFF8C', '#F9D057', '#F29E2E', '#E76818', '#D7191C'];
// the scale
var scale = {
x: d3.scaleLinear()
.range([-1, width]),
y: d3.scaleLinear()
.range([height, 0]),
};
var xBand = d3.scaleBand().domain(xLabels).range([0, width]),
yBand = d3.scaleBand().domain(yLabels).range([height, 0]);
var axis = {
x: d3.axisBottom(scale.x).tickFormat((d, e) => xLabels[d]),
y: d3.axisLeft(scale.y).tickFormat((d, e) => yLabels[d]),
};
function updateScales(data){
scale.x.domain([0, d3.max(data, d => d.xKey)]),
scale.y.domain([ 0, d3.max(data, d => d.yKey)])
}
var colorScale = d3.scaleQuantile()
.domain([0, colors.length - 1, d3.max(dataset, function (d) {return d.val;})])
.range(colors);
var zoom = d3.zoom()
.scaleExtent([1, dotHeight])
.on("zoom", zoomed);
var tooltip = d3.select("body").append("div")
.attr("id", "tooltip")
.style("opacity", 0);
// SVG canvas
svg.call(zoom);
// Clip path
clip.attr("width", width)
.attr("height", height+dotHeight);
//Create X axis
var renderXAxis = xAxis
//.attr("transform", "translate(0," + scale.y(-0.5) + ")")
//.call(axis.x)
//Create Y axis
var renderYAxis = yAxis.call(axis.y);
function zoomed() {
d3.event.transform.y = 0;
d3.event.transform.x = Math.min(d3.event.transform.x, 5);
d3.event.transform.x = Math.max(d3.event.transform.x, (1 - d3.event.transform.k) * width);
// console.log(d3.event.transform)
// update: rescale x axis
renderXAxis.call(axis.x.scale(d3.event.transform.rescaleX(scale.x)));
// Make sure that only the x axis is zoomed
heatDotsGroup.attr("transform", d3.event.transform.toString().replace(/scale\((.*?)\)/, "scale($1, 1)"));
}
svg.call(renderPlot, dataset)
function renderPlot(selection, dataset){
//Do the axes
updateScales(dataset)
selection.select('.y.axis').call(axis.y)
selection.select('.x.axis')
.attr("transform", "translate(0," + scale.y(-0.5) + ")")
.call(axis.x)
// Do the chart
const update = heatDotsGroup.selectAll("ellipse")
.data(dataset);
update
.enter()
.append("ellipse")
.merge(update)
.attr("cx", function (d) {return scale.x(d.xKey) - xBand.bandwidth();})
.attr("cy", function (d) {return scale.y(d.yKey) + yBand.bandwidth();})
.attr("rx", dotWidth)
.attr("ry", dotHeight)
.attr("fill", function (d) {
return colorScale(d.val);}
)
update.exit().remove();
}
};
#clickMe{
height:50px;
width:150px;
background-color:lavender;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Heatmap Chart</title>
<!-- Reference style.css -->
<!-- <link rel="stylesheet" type="text/css" href="style.css">-->
<!-- Reference minified version of D3 -->
<script src='https://d3js.org/d3.v4.min.js' type='text/javascript'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='heatmap_v4.js' type='text/javascript'></script>
</head>
<body>
<input id="clickMe" type="button" value="click me to push new data" onclick="run();" />
<div id='chart'>
<svg width="700" height="500">
<g class="focus">
<g class="xaxis"></g>
<g class="yaxis"></g>
</g>
</svg>
</div>
<script>
function run() {
var dataset = [];
for (let i = 1; i < 360; i++) { //360
for (j = 1; j < 7; j++) { //75
dataset.push({
xKey: i,
xLabel: "xMark " + i,
yKey: j,
yLabel: "yMark " + j,
val: Math.random() * 25,
})
}
};
heatmap(dataset)
}
$(document).ready(function() {});
</script>
</body>
</html>
The exit selection here is still empty as the size of the data array is fixed. D3 assumes the new data replaces the old, but it can't know that the new data should be represented as new elements, unless of course we specify a key function as noted in a now deleted comment. This may or may not be the desired functionality that you want.
I have a slightly different approach than Andrew.
A bunch of global variables will get messy when you have multiple charts.
When you click the button:
call the renderPlot(dataset)
check if we have a #clip element in the svg
if not: call heatmap(dataset)
Construct all the static stuff and append to the svg.
append a datum object to the svg with the variables needed for the update
fetch the datum from the svg
update the content of the svg using the datum object
function heatmap(dataset) {
var svg = d3.select("#chart")
.select("svg");
var xLabels = [],
yLabels = [];
for (i = 0; i < dataset.length; i++) {
if (i==0){
xLabels.push(dataset[i].xLabel);
var j = 0;
while (dataset[j+1].xLabel == dataset[j].xLabel){
yLabels.push(dataset[j].yLabel);
j++;
}
yLabels.push(dataset[j].yLabel);
} else {
if (dataset[i-1].xLabel == dataset[i].xLabel){
//do nothing
} else {
xLabels.push(dataset[i].xLabel);
}
}
};
var margin = {top: 0, right: 25,
bottom: 60, left: 75};
var width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var dotSpacing = 0,
dotWidth = width/(2*(xLabels.length+1)),
dotHeight = height/(2*yLabels.length);
var daysRange = d3.extent(dataset, function (d) {return d.xKey}),
days = daysRange[1] - daysRange[0];
var hoursRange = d3.extent(dataset, function (d) {return d.yKey}),
hours = hoursRange[1] - hoursRange[0];
var tRange = d3.extent(dataset, function (d) {return d.val}),
tMin = tRange[0],
tMax = tRange[1];
var colors = ['#2C7BB6', '#00A6CA', '#00CCBC', '#90EB9D', '#FFFF8C', '#F9D057', '#F29E2E', '#E76818', '#D7191C'];
// the scale
var scale = {
x: d3.scaleLinear()
.range([-1, width]),
y: d3.scaleLinear()
.range([height, 0]),
};
var xBand = d3.scaleBand().domain(xLabels).range([0, width]),
yBand = d3.scaleBand().domain(yLabels).range([height, 0]);
var axis = {
x: d3.axisBottom(scale.x).tickFormat((d, e) => xLabels[d]),
y: d3.axisLeft(scale.y).tickFormat((d, e) => yLabels[d]),
};
var colorScale = d3.scaleQuantile()
.domain([0, colors.length - 1, d3.max(dataset, function (d) {return d.val;})])
.range(colors);
var zoom = d3.zoom()
.scaleExtent([1, dotHeight])
.on("zoom", zoomed);
var tooltip = d3.select("body").append("div")
.attr("id", "tooltip")
.style("opacity", 0);
// SVG canvas
svg .attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.call(zoom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Clip path
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height+dotHeight);
// Heatmap dots
var heatDotsGroup = svg.append("g")
.attr("clip-path", "url(#clip)")
.append("g");
//Create X axis
var renderXAxis = svg.append("g")
.attr("class", "x axis")
//.attr("transform", "translate(0," + scale.y(-0.5) + ")")
//.call(axis.x)
//Create Y axis
var renderYAxis = svg.append("g")
.attr("class", "y axis")
.call(axis.y);
function zoomed() {
d3.event.transform.y = 0;
d3.event.transform.x = Math.min(d3.event.transform.x, 5);
d3.event.transform.x = Math.max(d3.event.transform.x, (1 - d3.event.transform.k) * width);
// console.log(d3.event.transform)
// update: rescale x axis
renderXAxis.call(axis.x.scale(d3.event.transform.rescaleX(scale.x)));
// Make sure that only the x axis is zoomed
heatDotsGroup.attr("transform", d3.event.transform.toString().replace(/scale\((.*?)\)/, "scale($1, 1)"));
}
var chartData = {};
chartData.scale = scale;
chartData.axis = axis;
chartData.xBand = xBand;
chartData.yBand = yBand;
chartData.colorScale = colorScale;
chartData.heatDotsGroup = heatDotsGroup;
chartData.dotWidth = dotWidth;
chartData.dotHeight = dotHeight;
svg.datum(chartData);
//svg.call(renderPlot, dataset)
}
function updateScales(data, scale){
scale.x.domain([0, d3.max(data, d => d.xKey)]),
scale.y.domain([0, d3.max(data, d => d.yKey)])
}
function renderPlot(dataset){
var svg = d3.select("#chart")
.select("svg");
if (svg.select("#clip").empty()) { heatmap(dataset); }
chartData = svg.datum();
//Do the axes
updateScales(dataset, chartData.scale);
svg.select('.y.axis').call(chartData.axis.y)
svg.select('.x.axis')
.attr("transform", "translate(0," + chartData.scale.y(-0.5) + ")")
.call(chartData.axis.x)
// Do the chart
const update = chartData.heatDotsGroup.selectAll("ellipse")
.data(dataset);
update
.enter()
.append("ellipse")
.attr("rx", chartData.dotWidth)
.attr("ry", chartData.dotHeight)
.merge(update)
.transition().duration(800)
.attr("cx", function (d) {return chartData.scale.x(d.xKey) - chartData.xBand.bandwidth();})
.attr("cy", function (d) {return chartData.scale.y(d.yKey) + chartData.yBand.bandwidth();})
.attr("fill", function (d) { return chartData.colorScale(d.val);} );
update.exit().remove();
}
#clickMe{
height:50px;
width:150px;
background-color:lavender;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Heatmap Chart</title>
<!-- Reference style.css -->
<!-- <link rel="stylesheet" type="text/css" href="style.css">-->
<!-- Reference minified version of D3 -->
<script src='https://d3js.org/d3.v4.min.js' type='text/javascript'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='heatmap_v4.js' type='text/javascript'></script>
</head>
<body>
<input id="clickMe" type="button" value="click me to push new data" onclick="run();" />
<div id='chart'>
<svg width="700" height="500">
<g class="focus">
<g class="xaxis"></g>
<g class="yaxis"></g>
</g>
</svg>
</div>
<script>
function run() {
var dataset = [];
for (let i = 1; i < 360; i++) { //360
for (j = 1; j < 7; j++) { //75
dataset.push({
xKey: i,
xLabel: "xMark " + i,
yKey: j,
yLabel: "yMark " + j,
val: Math.random() * 25,
})
}
};
renderPlot(dataset)
}
$(document).ready(function() {});
</script>
</body>
</html>

Trying to transfer Tributary D3.js example into JSFiddle

I'm rather a beginner at both JS and D3.js; my JSFiddle is here.
JSHint shows no errors, so I think I'm doing the D3 wrong.
I'm trying to do the same thing as in these questions, adapting a Tributary example to run outside of that platform: "Exporting" a Tributary example that makes use of the tributary object - d3.js and Getting horizontal stack bar example to display using d3.js (I'm even adapting the same code as the latter) Unfortunately, there is no corrected JSFiddle or other example in either answer
Here's my code:
var VanillaRunOnDomReady = function() {
var margins = {
top: 12,
left: 48,
right: 24,
bottom: 24
};
var data = [
{"key":"Nonviolent", "cat1":0.69, "cat2":0.21, "cat3":0.10},
{"key":"Violent", "cat1":0.53, "cat2":0.29, "cat3":0.18}
];
var catnames = {cat1: "No mental illness",
cat2: "Mild mental illness",
cat3: "Moderate or severe mental illness"};
var svg = d3.select('body')
.append('svg')
.attr('width', width + margins.left + margins.right)
.attr('height', height + margins.top + margins.bottom)
.append('g')
.attr('transform', 'translate(' + margins.left + ',' + margins.top + ')');
var n = 3, // number of layers
m = data.length, // number of samples per layer
stack = d3.layout.stack(),
labels = data.map(function(d) {return d.key;}),
//go through each layer (cat1, cat2 etc, that's the range(n) part)
//then go through each object in data and pull out that objects's catulation data
//and put it into an array where x is the index and y is the number
layers = stack(d3.range(n).map(function(d) {
var a = [];
for (var i = 0; i < m; ++i) {
a[i] = {x: i, y: data[i]['cat' + (d+1)]};
}
return a;
})),
//the largest single layer
yGroupMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y; }); }),
//the largest stack
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: 50},
width = 677 - margin.left - margin.right,
height = 533 - margin.top - margin.bottom;
var y = d3.scale.ordinal()
.domain(d3.range(m))
.rangeRoundBands([2, height], 0.08);
var x = d3.scale.linear()
.domain([0, yStackMax])
.range([0, width]);
var color = d3.scale.linear()
.domain([0, n - 1])
.range(["#aad", "#556"]);
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("y", function(d) { return y(d.x); })
.attr("x", function(d) { return x(d.y0); })
.attr("height", y.rangeBand())
.attr("width", function(d) { return x(d.y); });
var yAxis = d3.svg.axis()
.scale(y)
.tickSize(1)
.tickPadding(6)
.tickValues(labels)
.orient("left");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
};
I think you are just missing a (); at the end of your function and before the semicolon. That would make it self executing. I forked your fiddle.
var VanillaRunOnDomReady = function() {
var margins = {
top: 12,
left: 48,
right: 24,
bottom: 24
};
var data = [
{"key":"Nonviolent", "cat1":0.69, "cat2":0.21, "cat3":0.10},
{"key":"Violent", "cat1":0.53, "cat2":0.29, "cat3":0.18}
];
var catnames = {cat1: "No mental illness",
cat2: "Mild mental illness",
cat3: "Moderate or severe mental illness"};
var svg = d3.select('body')
.append('svg')
.attr('width', width + margins.left + margins.right)
.attr('height', height + margins.top + margins.bottom)
.append('g')
.attr('transform', 'translate(' + margins.left + ',' + margins.top + ')');
var n = 3, // number of layers
m = data.length, // number of samples per layer
stack = d3.layout.stack(),
labels = data.map(function(d) {return d.key;}),
//go through each layer (cat1, cat2 etc, that's the range(n) part)
//then go through each object in data and pull out that objects's catulation data
//and put it into an array where x is the index and y is the number
layers = stack(d3.range(n).map(function(d) {
var a = [];
for (var i = 0; i < m; ++i) {
a[i] = {x: i, y: data[i]['cat' + (d+1)]};
}
return a;
})),
//the largest single layer
yGroupMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y; }); }),
//the largest stack
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: 50},
width = 677 - margin.left - margin.right,
height = 533 - margin.top - margin.bottom;
var y = d3.scale.ordinal()
.domain(d3.range(m))
.rangeRoundBands([2, height], 0.08);
var x = d3.scale.linear()
.domain([0, yStackMax])
.range([0, width]);
var color = d3.scale.linear()
.domain([0, n - 1])
.range(["#aad", "#556"]);
var svg = d3.select("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); });
layer.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("y", function(d) { return y(d.x); })
.attr("x", function(d) { return x(d.y0); })
.attr("height", y.rangeBand())
.attr("width", function(d) { return x(d.y); });
var yAxis = d3.svg.axis()
.scale(y)
.tickSize(1)
.tickPadding(6)
.tickValues(labels)
.orient("left");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
}();

Dynamically resizing of d3.js bar chart based on data

I'm building a set of bar charts that will be updated dynamically with json data.
There will be occasions where the x.domain value is equal to zero or null so in those cases I don't want to draw the rectangle, and would like the overall height of my chart to adjust. However, the bars are being drawn based on data.length which may contain 9 array values, but some of those values are zeros, but render a white space within the graph.
I've attached an image of what is happening. Basically there are 9 data entries and only one of those actually contains the positive value, but the bars are still being drawn for all 9 points.
Here is my code:
d3.json("data/sample.json", function(json) {
var data = json.cand;
var margin = {
top: 10,
right: 20,
bottom: 30,
left: 0
}, width = parseInt(d3.select('#graphic').style('width'), 10),
width = width - margin.left - margin.right -50,
bar_height = 55,
num_bars = (data.length),
bar_gap = 18,
height = ((bar_height + bar_gap) * num_bars);
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.ordinal()
.range([height, 0]);
var svg = d3.select('#graphic').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 dx = width;
var dy = (height / data.length) + 8;
// set y domain
x.domain([0, d3.max(data, function(d) {
return d.receipts;
})]);
y.domain(0, d3.max(data.length))
.rangeBands([0, data.length * bar_height ]);
var xAxis = d3.svg.axis().scale(x).ticks(2)
.tickFormat(function(d) {
return '$' + formatValue(d);
});
var yAxis = d3.svg.axis()
.scale(y)
.orient('left')
.ticks(0)
.tickFormat(function(d) {
return '';
});
// set height based on data
height = y.rangeExtent()[1] +12;
d3.select(svg.node().parentNode)
.style('height', (height + margin.top + margin.bottom) + 'px');
// bars
var bars = svg.selectAll(".bar")
.data (data, function (d) {
if (d.receipts >= 1) {
return ".bar";
} else {
return null;
}
})
.enter().append('g');
bars.append('rect')
.attr("x", function(d, i) {
return 0;
})
.attr("y", function(d, i) {
if (d.receipts >= 1) {
return i * (bar_height + bar_gap - 4);
}else {
return null;
}
})
.attr("width", function(d, i) {
if (d.receipts >= 1) {
return dx * d.receipts;
} else {
return 0;
}
});
//y and x axis
svg.append('g')
.attr('class', 'x axis bottom')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis.orient('bottom'));
svg.append('g')
.call(yAxis.orient('left'));
});

Categories