d3 v4: Data join for bar chart - javascript

I am trying to adopt bar chart example here to understand data joins in d3 v4. Enter selection works fine but I am unable to figure out how to update. Here is what I have so far: https://jsfiddle.net/hackygkL/
Can someone please help me.
var width = 420,
barheight = 30;
var svg = d3.select('#bar-chart')
.append('svg')
.attr('width', width + 50)
.attr('height', 1000);
var scale = d3.scaleLinear()
.range([0, width]);
function createBar(data) {
scale.domain([0, d3.max(data)]);
var barGroups = svg.selectAll('g')
.data(data, function(d){return d;});
barGroups.exit().remove();
var enterGroup = barGroups.enter() //ENTER
.append('g')
.merge(barGroups) //UPDATE
.attr("transform", function(d, i){
return "translate(0, " + barheight * i + ")";
});
var bars = barGroups.selectAll('rect');
enterGroup.append('rect') //ENTER
.attr('class', 'bar')
.attr('height', barheight - 1)
.merge(bars) //UPDATE
.attr('width', function(d){
return scale(d);
})
.attr('fill', 'steelblue');
var texts = barGroups.selectAll('text');
enterGroup.append("text") //ENTER
.attr('class', 'text')
.attr("y", barheight / 2)
.attr("dy", ".35em")
.merge(texts) //UPDATE
.attr("x", function(d) { return scale(d) + 10; })
.text(function(d) { return d;});
}

Seems to work after merging the groups first, then updating the rects and texts:
https://bl.ocks.org/ckothari/699b112b6e1376779e65973bbabdced6

Related

How to scale y-Axis in d3.js according to data input correctly

I created a small Barchart. My problem is that the y-axis doesn't scale according to my dataset. Here is a screenshot:
So as you can see the 313 is a little bit above the 800 scale. I would like the 300 to be at the 300. I tweaked with the scalings but I just end up messing it up completely. I am very new to D3.js so I hope someone can help.
Here is my code:
var svgWidth = 1000, svgHeight = 800;
var barWidth = svgWidth / month_description.length;
var barPadding = 5;
var svg = d3.select('svg')
.attr("width", svgWidth)
.attr("height", svgHeight);
var barChart = svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("y", function(d) {
return svgHeight - d - 20
})
.attr("x", function(d, i) {
return i + 10;
})
.attr("height", function(d) {
return d;
})
.attr("width", barWidth - barPadding)
.attr("class", "bar")
.attr("transform", function (d, i) {
var translate = [barWidth * i, 0];
return "translate("+ translate +")";
});
var text = svg.selectAll("text")
.data(data)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("y", function(d, i) {
return svgHeight - 20;
})
.attr("x", function(d, i) {
return barWidth * i + 35;
})
.attr("fill", "white");
var xScale = d3.scaleLinear()
.domain([0, d3.max(month_description)])
.range([0, svgWidth]);
var yScale = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([svgHeight, 0]);
var x_axis = d3.axisBottom()
.scale(xScale);
var y_axis = d3.axisLeft()
.scale(yScale);
svg.append("g")
.attr("transform", "translate(50, 10)")
.call(y_axis);
var xAxisTranslate = svgHeight - 20;
svg.append("g")
.attr("transform", "translate(50, " + xAxisTranslate +")")
.call(x_axis);
Help is very much appreciated. Thanks very much in advance!!

Conditional Bar Chart with D3

I have a D3 visualization with a map and a bar chart. I am trying to get the bar chart to change depending on which circle on the map is clicked. Not sure how to do this. I have a function in my bar_chart.js file named update(newData) and a few extra arrays for the different circles on the map. Here is the link to the bl.ocks for the map and bar char.
js code for map
var myData = [21, 3, 5, 21, 15];
//Width and height
var w = 200;
var h = 125;
var yScale = null;
function draw(initialData) {
var xScale = d3.scale.ordinal()
.domain(d3.range(initialData.length))
.rangeRoundBands([0, w], 0.05);
yScale = d3.scale.linear()
.domain([0, d3.max(initialData)])
.range([0, h]);
//Create SVG element
var svg = d3.select("#chart")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(initialData)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", "steelblue");
svg.selectAll("text")
.data(initialData)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
}
draw(myData);
//update function
function update(newData) {
yScale.domain([0, d3.max(newData)]);
var rects = d3.select("#chart svg")
.selectAll("rect")
.data(newData);
// enter selection
rects
.enter().append("rect");
// update selection
rects
.transition()
.duration(300)
.attr("y", function(d) {
return h - yScale(d);
})
.attr("height", function(d) {
return yScale(d);
})
// exit selection
rects
.exit().remove();
var texts = d3.select("#chart svg")
.selectAll("text")
.data(newData);
// enter selection
texts
.enter().append("rect");
// update selection
texts
.transition()
.duration(300)
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.text(function(d) {
return d;
})
// exit selection
texts
.exit().remove();
}
var mk = [10,17,20,14,8];
var cn = [18,4,9,20,15];
var nd = [5,12,7,15,21];
d3.select("#update").on("click", function() { update(newData); });
You have to incorporate the barchart data in your cities.csv file.
In the on-click handler of cities.csv where you show the tooltip you have to transform the data from the CSV into an array and call the bar chart update() method with this array.
One way of doing is to replace the , from the bar chart data with another char and split the string and convert the parts to numbers.
var cityData = d.barchart.split('#').map(Number);
update(cityData);
You also have to set the attributes of the new rects and texts of the bar chart. And the x-position will change if the number of bars change.

update d3 chart with new data

I want to update the bar chart with new data and I looked over this question:
How to update d3.js bar chart with new data
But it is not working for me. Probably because I don't know where to put the exit().remove() functions within my code. I tried putting this line
svg.selectAll("rect").exit().remove();
below the create bars section but it just removes all of the labels. Then, if I put it right after the create labels portion it removes the chart entirely. How can I get the update button change the chart with new data?
function draw(data) {
//Width and height
var w = 250;
var h = 250;
var xScale = d3.scale.ordinal()
.domain(d3.range(data.length))
.rangeRoundBands([0, w], 0.05);
var yScale = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, h]);
//Create SVG element
var svg = d3.select("#chart")
.append("svg")
.attr("width", w)
.attr("height", h);
//Create bars
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", "steelblue");
//Create labels
svg.selectAll("text")
.data(data)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
};
function update() {
var data = [ 25, 22, 18, 15, 13 ];
draw(data);
}
var data = [ 21, 3, 5, 21, 15 ];
window.onload = draw(data);
With d3v3 (as I can see from your code you use this version) you should update your chart this way:
In update function set the new domain for yScale:
function update(newData) {
yScale.domain([0, d3.max(newData)]);
After that, apply new selection with selectAll("rect").data(newData), store selection in rects variable and set new value for appropriate attributes (if you do not want animation effect, remove .transition() .duration(300)):
var rects = d3.select("#chart svg")
.selectAll("rect")
.data(newData);
// enter selection
rects
.enter().append("rect");
// update selection
rects
.transition()
.duration(300)
.attr("y", function(d) {
return h - yScale(d);
})
.attr("height", function(d) {
return yScale(d);
})
Exit selection with exit method:
rects
.exit().remove();
Do the same way with text. I rewrite your code, look at the example in a hidden snippet below:
var myData = [21, 3, 5, 21, 15];
//Width and height
var w = 250;
var h = 250;
var yScale = null;
function draw(initialData) {
var xScale = d3.scale.ordinal()
.domain(d3.range(initialData.length))
.rangeRoundBands([0, w], 0.05);
yScale = d3.scale.linear()
.domain([0, d3.max(initialData)])
.range([0, h]);
//Create SVG element
var svg = d3.select("#chart")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(initialData)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", "steelblue");
svg.selectAll("text")
.data(initialData)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
}
function update(newData) {
yScale.domain([0, d3.max(newData)]);
var rects = d3.select("#chart svg")
.selectAll("rect")
.data(newData);
// enter selection
rects
.enter().append("rect");
// update selection
rects
.transition()
.duration(300)
.attr("y", function(d) {
return h - yScale(d);
})
.attr("height", function(d) {
return yScale(d);
})
// exit selection
rects
.exit().remove();
var texts = d3.select("#chart svg")
.selectAll("text")
.data(newData);
// enter selection
texts
.enter().append("rect");
// update selection
texts
.transition()
.duration(300)
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.text(function(d) {
return d;
})
// exit selection
texts
.exit().remove();
}
window.onload = draw(myData);
setInterval(function() {
var data = d3.range(5).map(function() {
return parseInt(Math.random() * 20 + 1);
});
update(data);
}, 3000)
<div id="chart"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>

Chart not updating with new data with transitions in D3

Trying to do a simple replace data/transition with D3 but it's not updating. I'm not getting an error and don't see anything odd when debugging. I feel like i'm missing something super simple and just overlooking. The more eyes, the better!
Here's my D3 code:
var labels = ['Opens', 'Clicks', 'Unsubscribe'],
data = [4, 8, 15],
chart,
x,
y,
gap = 2,
width = 450,
leftWidth = 100,
barHeight = 40,
barHeightInner = (barHeight / 2),
barTopMargin = (barHeight - barHeightInner) / 2,
height = (barHeight + gap * 2) * labels.length + 30;
/* SET SVG + LEFT MARGIN */
chart = d3.select($("#graphArea")[0])
.append('svg')
.attr('class', 'chart')
.attr('width', leftWidth + width + 20)
.attr('height', height)
.append("g")
.attr("transform", "translate(10, 20");
x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, width]);
y = d3.scale.ordinal()
.domain(data)
.rangeBands([0, (barHeight + 2 * gap) * labels.length], 0.05);
/* CREATE BARS */
chart.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("x", leftWidth)
.attr("y", y)
.attr("width", x)
.attr("height", y.rangeBand())
.attr('class', 'bar-outer');
/* INNER BARS */
chart.selectAll("rect.inner")
.data(data)
.enter().append("rect")
.attr("x", leftWidth)
.attr("y", function(d){return y(d) + barTopMargin} )
.attr("width", function(d){return x(d)/2;})
.attr("height", barHeightInner)
.attr('class', 'bar-inner');
/* SET NAMED LABELS */
chart.selectAll("text.label")
.data(labels)
.enter().append("text")
.attr("x", leftWidth / 2 + 40)
.attr("y", function(d,i) {return i * y.rangeBand() + 20;})
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr('class', 'label')
.text(String);
function update(data) {
data = [20, 10, 3];
chart.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("x", leftWidth)
.attr("y", y)
.attr("width", x)
.attr("height", y.rangeBand())
.attr('class', 'bar-outer');
chart.selectAll("rect")
.data(data)
.exit()
.transition()
.duration(300)
.ease("exp")
.attr('width', 0)
.remove();
chart.selectAll("rect")
.data(data)
.transition()
.duration(300)
.ease("quad")
.attr("width", x)
.attr("height", y.rangeBand())
.attr("transform", function(d,i) { return "translate(" + [0, y(i)] + ")"});
It's kind of messy, sorry... but should be readable at least. I'm not sure why when update(data) it's not changing. Any advice would be greatly appreciated!
The main problems were with the application of the enter/update/exit pattern and also with forgetting to re-set the scale domains according to the new data. Here is the segment of interest:
function update() {
data = [20, 10, 3];
// must re-set scale domains with the new data
x.domain([0, d3.max(data)]);
y.domain(data);
var outer = chart.selectAll(".bar-outer")
.data(data);
// exit selection
outer
.exit()
.remove();
// enter selection
outer
.enter()
.append("rect")
.attr('class', 'bar-outer');
// update selection
outer
.transition()
.duration(500)
.ease("quad")
.attr("x", leftWidth)
.attr("y", y)
.attr("width", x)
.attr("height", y.rangeBand());
var inner = chart.selectAll(".bar-inner")
.data(data);
// exit selection
inner
.exit()
.remove();
// enter selection
inner
.enter()
.append("rect")
.attr('class', 'bar-inner');
// update selection
inner
.transition()
.duration(500)
.ease("quad")
.attr("x", leftWidth)
.attr("y", function (d) {
return y(d) + barTopMargin
})
.attr("width", function (d) {
return x(d) / 2;
})
.attr("height", barHeightInner);
};
Here is the complete FIDDLE.

unable to load csv to d3 scatter plot

Below is my d3 code, it works perfectly if I mention the dataset with its numbers. However, when i want to take data from a csv file, it doesn't not accept it.
*ERROR
Error: Invalid value for <circle> attribute cx="NaN"
Here how the csv looks like:
t Or
16610 20635
14920 19532
13131 14814
15882 15745
15769 14993
15989 22557
14895 15387
17915 19758
Although if I try in google chrome,
console.log(dataset)
I get the data from csv but when i run it to apply, it just doesn't work in the browser.
I am using brackets as my IDE and google chrome as my default browser.
<body>
<h1> Hello World!! </h1>
<script type="text/javascript">
var dataset;
d3.csv("t.csv", function(d) {
dataset = d;
var h = 500;
var w = 1200;
var padding = 30;
var xscale = d3.scale.linear()
.domain([0,d3.max(dataset, function(d) { return d[0];})])
.range([padding, w- padding*2]);
var yscale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[1];})])
.range([h-padding,padding]);
var rscale = d3.scale.linear()
.domain([0,d3.max(dataset , function(d) { return d[1];})])
.range([5,30]);
var xAxis = d3.svg.axis()
.scale(xscale)
.orient("bottom");
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var circle = svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d) { return xscale(d[0]);})
.attr("cy", function(d) { return yscale(d[1]);})
.attr("r",function(d) { return rscale(d[1]);})
.on("mouseover", function(){d3.select(this).style("fill", "yellow");})
.on("mouseout", function(){d3.select(this).style("fill", function(dataset) { return "rgb(0,0," +(d*10) + ")";});});
var text = svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) { return d[0] + "," + d[1];})
.attr("x", function(d) { return xscale(d[0]);})
.attr("y", function(d) { return yscale(d[1]);})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill" ,"red");
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0, " + (h - padding) +")")
.call(xAxis);
});
</script>
</body>
I just tweaked my above code. using the below which i found right here
It worked
var dataset;
d3.csv("t.csv", function(error, d) {
dataset = d.map(function(d) { return [ +d["t"], +d["Or"] ]; });

Categories