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>
Related
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.
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
I have a bar chart that updates based on the results selected in a drop-down menu. When I change the selcetion, I get negaitve "y" values. It seems that my domain does not get updated with the new data. When I hard code the domain, my "y" are what I expect them to be. Anyone knows why ? Any other other comments (formatting, etc) welcomed.
var new_data;
//Create SVG margins and patting for the interior
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
//Create Scale
var xScale = d3
.scale
.ordinal()
.rangeRoundBands([margin.left, width], .1);
;
var yScale = d3
.scale
.linear()
.range([height, 0])
;
var xAxis = d3
.svg
.axis()
.scale(xScale)
.orient("bottom")
.tickPadding([5])
;
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(10)
;
//Create SVG with the above specs
var svg = d3.select("#container")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
;
svg
.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
;
svg
.append("g")
.attr("class", "y axis")
.append("text") // just for the title (ticks are automatic)
.attr("transform", "rotate(-90)") // rotate the text!
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("frequency")
;
var temp = svg
.append("g")
.attr("class", "domx")
;
d3.csv("data3.csv", function(error, csv_data) {
// Filter the dataset to only get dept_1
var new_data = csv_data.filter(function(d) {
return d['dept'] == 'dept_1';
});
// function to handle histogram.
function histoGram(new_data){
//Create Scales
xScale
.domain(new_data.map(function(d) {return d.Pos;}))
;
yScale
// .domain([0, d3.max(new_data, function(d) { return d.Value; })])
.domain([0, d3.max(new_data, function(d) { return d.Value; })])
// .domain([0, 20])
;
svg
.select(".x.axis")
.transition()
.duration(1500)
.call(xAxis)
;
svg
.select(".y.axis")
.transition()
.duration(1500)
.call(yAxis)
;
// Data Join
var MyGroups = temp
.selectAll("g")
.data(new_data);
;
var MyGroupsEnter = MyGroups
.enter()
.append("g")
;
//Update
MyGroups
.attr("class", "update")
;
//Enter
MyGroupsEnter
.append("rect")
.attr("class", "enter")
.attr("x", function(d) { return xScale(d.Pos); })
.attr("y", function(d) { return (yScale(d.Value));})
.attr("width", xScale.rangeBand())
.attr("height", function(d) { return (height - yScale(d.Value)); })
.text(function(d) { return d.Value; })
.attr("fill", function(d) {return "rgb(0, 0, 0)";})
.style("fill-opacity", 0.2)
;
MyGroupsEnter
.append("text")
.attr("class", "text")
.text(function(d) { return d.Value; })
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "black")
.attr("text-anchor", "middle")
.attr("x", function(d) { return xScale(d.Pos) + xScale.rangeBand()/2; })
.attr("y", function(d) { return yScale(d.Value) - 10; })
;
//Enter + Update
MyGroups
.transition()
.duration(1500)
.select("rect")
.attr("x", function(d) { return xScale(d.Pos); })
.attr("width", xScale.rangeBand())
.attr("y", function(d) { return (yScale(d.Value));})
.attr("height", function(d) { return (height - yScale(d.Value)); })
.text(function(d) { return d.Value; })
.style("fill-opacity", 1) // set the fill opacity
.attr("fill", function(d) {return "rgb(0, 0, " + (d.Value * 30) + ")";})
;
MyGroups
.transition()
.duration(1500)
.select("text")
.attr("class", "text")
.text(function(d) { return d.Value; })
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "black")
.attr("text-anchor", "middle")
.attr("x", function(d) { return xScale(d.Pos) + xScale.rangeBand()/2; })
.attr("y", function(d) { return yScale(d.Value) - 8; })
;
MyGroups
.exit()
.transition()
.duration(1500)
.remove()
;
}
histoGram(new_data);
var options = ["dept_1","dept_2","dept_3"];
var dropDown = d3
.select("#sel_button")
.append("select")
.attr("name", "options-list")
.attr("id", "id-name");
var options = dropDown
.selectAll("option")
.data(options)
.enter()
.append("option");
options
.text(function (d) { return d; })
.attr("value", function (d) { return d; });
d3.select("#id-name")
.on("change", function() {
var value = d3.select(this).property("value");
var new_data2 = csv_data.filter(function(d) {
return d['dept'] == value;
});
histoGram(new_data2);
});
});
Here is the data:
dept,Pos,Value
dept_1,d1_p1,1
dept_1,d1_p10,10
dept_1,d1_p11,11
dept_1,d1_p12,12
dept_2,d2_p1,1.5
dept_2,d2_p2,3
dept_2,d2_p3,4.5
dept_2,d2_p4,6
dept_2,d2_p5,7.5
dept_2,d2_p6,9
dept_2,d2_p7,10.5
dept_2,d2_p8,12
dept_2,d2_p9,13.5
dept_2,d2_p10,15
dept_2,d2_p11,16.5
dept_2,d2_p12,17.5
dept_2,d2_p13,18.5
dept_3,d3_p1,5
dept_3,d3_p2,7
dept_3,d3_p3,10
Firgured out what was my problem. I hadn't defined the format of the values. The max function was returning the maximum number out of character values (9). I added the following piece of code prior to the domain function and everything now works fines.
csv_data.forEach(function(d) {
d.dept = d.dept;
d.Pos = d.Pos;
d.Value = +d.Value;
});
I'm new to D3 and pretty new to Javascript. My bar chart works as is, but when I add either block of commented out code attempting to add the tool-tip, instead of the tool-tip rendering on top of the bar chart, I get only the bars rendering along with the color fill transition. The x axis, y axis and the text within the bars disappears. What am I doing wrong here?
<script>
var employees = []
employees[0] = { name: "Bob", age: 31 }
employees[1] = { name: "Doug", age: 22 }
employees[2] = { name: "Christine", age: 58 }
employees[3] = { name: "Sarah", age: 40 }
var width = 700;
var height = 800;
//create scales
var widthScale = d3.scale.linear()
.domain([0, 58])
.range([0, width]);
var yScale = d3.scale.ordinal()
.domain(['200,000', '175,000', '150,000', '125,000', '100,000', '75,000', '50,000', '25,000', '0'])
.rangePoints([0, 300]);
//create axis using scales
var xAxis = d3.svg.axis()
.ticks(10)
.tickSize(2)
.scale(widthScale);
var yAxis = d3.svg.axis()
.orient('left')
.tickSize(2)
.scale(yScale)
//colorscale for bar color transition
var colorScale = d3.scale.linear()
.domain([0, 58])
.range(["green", "yellow"]);
//tooltip------------------------------------------------
var tooltip = d3.select("body")
.append("div")
.attr("class", "mytooltip")
.style("position", "absolute")
.style("background", "white")
.style("opacity", "0")
.style("display", "none");
//create canvas
var canvas = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g") //create a group
.attr("transform", "translate(150, 15)") //right, down
//create bars & add bars to canvas using data
var bars = canvas.selectAll("rect")
.data(employees)
.enter()
.append("rect")
.attr("y", function (d, i) { return i * 25; })
.attr("width", 0)
.attr("height", 20)
.transition()
.delay(function (d, i) { return i * 100; })
.duration(600)
.attr("width", function (d) { return widthScale(d.age); })
.attr("height", 20)
.attr("fill", function (d) { return colorScale(d.age); })
.attr("y", function (d, i) { return i * 25; })
//add tooltip--------------------------------------------------
//.on('mouseover', function (d) {
// tooltip.transition()
// .style('opacity', .8)
// tooltip.html(d)
// .style('left', (d3.event.pageX - 35) + 'px')
// .style('top', (d3.event.pageY - 30) + 'px')
// });
//add text to bars
canvas.selectAll("text")
.data(employees)
.enter()
.append("text")
.attr("fill", "black")
.attr("y", function (d, i) { return i * 25 + 14; })
.text(function (d) { return d.name });
//append a group to canvas, transform & place xAxis on canvas
canvas.append("g")
.attr("transform", "translate(0, 300)")
.call(xAxis);
//append a group to canvas, transform & place yAxis on canvas
canvas.append("g")
.attr("transform", "translate(0, 0)")
.call(yAxis);
//add tooltip-------------------------------------------
//canvas.append("g")
// .on("mouseover", function (d) {
// d3.select(this)
// .transition()
// .duration(500)
// .attr("x", function (d) { return x(d.age) - 30; })
// .style("cursor", "pointer")
// });
</script>
Apply the mouse listener to the bars and show/hide tooltip div using css opacity.
var employees = [{
name: "Bob",
age: 31
}, {
name: "Doug",
age: 22
}, {
name: "Sarah",
age: 40
}];
var width = 700;
var height = 800;
//create scales
var widthScale = d3.scale.linear()
.domain([0, 58])
.range([0, width]);
var yScale = d3.scale.ordinal()
.domain(['200,000', '175,000', '150,000', '125,000', '100,000', '75,000', '50,000', '25,000', '0'])
.rangePoints([0, 300]);
//create axis using scales
var xAxis = d3.svg.axis()
.ticks(10)
.tickSize(2)
.scale(widthScale);
var yAxis = d3.svg.axis()
.orient('left')
.tickSize(2)
.scale(yScale)
//colorscale for bar color transition
var colorScale = d3.scale.linear()
.domain([0, 58])
.range(["green", "yellow"]);
//add tooltip------------------------------------------------
var tooltip = d3.select("body")
.append("div")
.attr("class", "d3-tip")
.style("position", "absolute")
.style("opacity", 0);
//create canvas
var canvas = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g") //create a group
.attr("transform", "translate(150, 15)") //right, down
//create bars & add bars to canvas using data
var bars = canvas.selectAll(".bar")
.data(employees)
.enter()
.append("g")
.attr("class","bar");
bars.append("rect")
.attr("y", function(d, i) {
return i * 25;
})
.attr("width", 0)
.attr("height", 20)
.transition()
.delay(function(d, i) {
return i * 100;
})
.duration(600)
.attr("width", function(d) {
return widthScale(d.age);
})
.attr("height", 20)
.attr("fill", function(d) {
return colorScale(d.age);
})
.attr("y", function(d, i) {
return i * 25;
});
//add text to bars
bars.selectAll("text")
.data(employees)
.enter()
.append("text")
.attr("fill", "black")
.attr("y", function(d, i) {
return i * 25 + 14;
})
.text(function(d) {
return d.name
});
//append a group to canvas, transform & place xAxis on canvas
canvas.append("g")
.attr("transform", "translate(0, 300)")
.call(xAxis);
//append a group to canvas, transform & place yAxis on canvas
canvas.append("g")
.attr("transform", "translate(0, 0)")
.call(yAxis);
//show/hide tooltip-------------------------------------------
canvas.selectAll(".bar")
.on("mouseover", function(d) {
var pos = d3.mouse(this);
console.log(pos);
tooltip
.transition()
.duration(500)
.style("opacity", 1)
.style("left", d3.event.x + "px")
.style("top", d3.event.y + "px")
.text(d.name);
})
.on("mouseout", function() {
tooltip.style("opacity", 0);
});
.d3-tip {
line-height: 1;
font-weight: bold;
padding: 12px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
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"] ]; });