I am working on this project with D3js and I have come across a problem now.
When I have more data, the bars of my barchart will append correctly in the same line as the name but when I fetch less data from my database, the bars will "loose control" and append higher than their name and causing a bad view of my chart.
Here's a picture of what I'll have if I load more data do it.
And here's my second picture of the chart if I load less data.
I don't really understand what I am missing here but I believe is something with the height of the Y-axis and the bars y-position. Can you please help me sort this out?
Here is my code:
var margin = { top: 20, right: 30, bottom: 40, left: 90 },
width = 360 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
.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 + ")");
// Parse the Data
var data2 = d3.json("/Events/BarChart/4").then(function (data) {
console.log(data);
// Add X axis
var x = d3.scaleLinear()
.domain([0, 5])
.range([0, width]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.selectAll("text")
.attr("transform", "translate(-10,0)rotate(-45)")
.style("text-anchor", "end")
;
// Y axis
var y = d3.scaleBand()
.range([0, height])
.domain(data.map(function (d) { return d.name; }))
svg.append("g")
.call(d3.axisLeft(y))
//Bars
svg.selectAll("myRect")
.data(data)
.enter()
.append("rect")
.attr("x", 4)
.attr("y", function (d) { return y(d.name) + 10; })
.attr("width", function (d) { return x(d.value); })
.attr("height", 20)
.attr("fill", function (d) {
if (d.value > 1) {
return "rgb(51, 80, 92)";
}
else if (d.value > 1 && d.value < 4) {
return "rgb(118, 161, 179)"
}
else {
return "rgb(171, 209, 224)";
}
})
})
The issue arises because you manually assign each rectangle a height of 20 pixels, but you give the scale a range of 0 - 240 (the value of height). The scale will divide the range into equal segments (bands), one for each value in its domain. When you have only two values in the domain they will have bands of 120 px each (reduced if there is padding). Nowhere does the scale "know" you have assigned a height of just 20 px for each bar; afterall, you told it to spread values evenly over a range of 0 - 240. These conflicting instructions are why your bars aren't aligned with your axis.
When using d3 scales you will find it much easier if you use the scale for both axis and drawing the data itself (rects/circles/etc): this way they will always be aligned.
The d3 band scale offers a convenient method: scale.bandwidth(), this returns the length/width/height of a band in the scale: at its simplest (without padding) it is the size of the range divided by how many distinct values are in the domain. We can use this value to set bar height:
var margin = { top: 20, right: 30, bottom: 40, left: 90 },
width = 360 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
.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 data = [
{name: "a", value: 1},
{name: "b", value: 2}
]
// Add X axis
var x = d3.scaleLinear()
.domain([0, 5])
.range([0, width]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.selectAll("text")
.attr("transform", "translate(-10,0)rotate(-45)")
.style("text-anchor", "end")
;
// Y axis
var y = d3.scaleBand()
.range([0, height])
.domain(data.map(function (d) { return d.name; }))
svg.append("g")
.call(d3.axisLeft(y))
//Bars
svg.selectAll("myRect")
.data(data)
.enter()
.append("rect")
.attr("x", 4)
.attr("y", function (d) { return y(d.name); })
.attr("width", function (d) { return x(d.value); })
.attr("height", y.bandwidth())
.attr("fill", function (d) {
if (d.value > 1) {
return "rgb(51, 80, 92)";
}
else if (d.value > 1 && d.value < 4) {
return "rgb(118, 161, 179)"
}
else {
return "rgb(171, 209, 224)";
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="my_dataviz"></div>
I also noticed that you add 10 pixels to the y value of each bar: this was probably to manually align the bars better with multiple data entries. Generally this will cause problems (unless manually correcting for them): scale(value) and scale.bandwidth() for y/x and height/width respectively produces bars centered on axis ticks. If you want padding (space between the bars), it is simplest to set that using the scale: scale.padding(number) where number is a value between 0 and 1 representing the portion of each segment that is empty:
var margin = { top: 20, right: 30, bottom: 40, left: 90 },
width = 360 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
.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 data = [
{name: "a", value: 1},
{name: "b", value: 2}
]
// Add X axis
var x = d3.scaleLinear()
.domain([0, 5])
.range([0, width]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.selectAll("text")
.attr("transform", "translate(-10,0)rotate(-45)")
.style("text-anchor", "end")
;
// Y axis
var y = d3.scaleBand()
.range([0, height])
.padding(0.1)
.domain(data.map(function (d) { return d.name; }))
svg.append("g")
.call(d3.axisLeft(y))
//Bars
svg.selectAll("myRect")
.data(data)
.enter()
.append("rect")
.attr("x", 4)
.attr("y", function (d) { return y(d.name); })
.attr("width", function (d) { return x(d.value); })
.attr("height", y.bandwidth())
.attr("fill", function (d) {
if (d.value > 1) {
return "rgb(51, 80, 92)";
}
else if (d.value > 1 && d.value < 4) {
return "rgb(118, 161, 179)"
}
else {
return "rgb(171, 209, 224)";
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="my_dataviz"></div>
But what if you don't want 120 px wide segments? You want your bars to be always 20-ish pixels, regardless of how many bars you have. Well we can modify the range of the scale to reflect the length of the domain:
var margin = { top: 20, right: 30, bottom: 40, left: 90 },
width = 360 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
.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 data = [
{name: "a", value: 1},
{name: "b", value: 2}
]
// Add X axis
var x = d3.scaleLinear()
.domain([0, 5])
.range([0, width]);
svg.append("g")
.attr("transform", "translate(0," + data.length*20 + ")")
.call(d3.axisBottom(x))
.selectAll("text")
.attr("transform", "translate(-10,0)rotate(-45)")
.style("text-anchor", "end")
;
// Y axis
var y = d3.scaleBand()
.domain(data.map(function (d) { return d.name; }))
.range([0, data.length*20])
.padding(0.1);
svg.append("g")
.call(d3.axisLeft(y))
//Bars
svg.selectAll("myRect")
.data(data)
.enter()
.append("rect")
.attr("x", 4)
.attr("y", function (d) { return y(d.name); })
.attr("width", function (d) { return x(d.value); })
.attr("height", y.bandwidth())
.attr("fill", function (d) {
if (d.value > 1) {
return "rgb(51, 80, 92)";
}
else if (d.value > 1 && d.value < 4) {
return "rgb(118, 161, 179)"
}
else {
return "rgb(171, 209, 224)";
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="my_dataviz"></div>
I also updated the transform for the x axis, you could go further an adjust svg height to be better sized as well
Related
I am new to D3 JS and looking for a customize solution which is not available out of the box in d3 JS.
Below code produced a bar chart which denotes no. of students against 3 different classes,
Question, Can I show Circle instead of bar? please suggest some code? Thanks!
//data
let data = [{ "noOfStudents": 30, "ClassName": "Class 1" }, { "noOfStudents": 42, "ClassName": "Class 2" }, { "noOfStudents": 38, "ClassName": "Class 3" }];
// set the dimensions and margins of the graph
var margin = { top: 20, right: 20, bottom: 30, left: 40 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// set the ranges
var x = d3.scaleBand().range([0, width]).padding(0.1);
var y = d3.scaleLinear().range([height, 0]);
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// get and format the data
data.forEach(function (d) {
d.noOfStudents = +d.noOfStudents;
});
// Scale the range of the data in the domains
x.domain(data.map(function (d) { return d.ClassName; }));
y.domain([0, d3.max(data, function (d) { return d.noOfStudents; })]);
// append the rectangles for the bar chart
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function (d) { return x(d.ClassName); })
.attr("width", x.bandwidth())
.attr("y", function (d) { return y(d.noOfStudents); })
.attr("height", function (d) { return height - y(d.noOfStudents); })
.text(function (d) { return d.noOfStudents; });
// add the x Axis
svg.append("g").attr("transform", "translate(0," + height + ")").call(d3.axisBottom(x));
// add the y Axis
svg.append("g").call(d3.axisLeft(y));
Instead of rectangles, just append circles:
svg.selectAll(".bar")
.data(data)
.enter().append("circle")
.attr("class", "bar")
.attr("cx", function (d) { return x(d.ClassName); })
.attr("cy", function (d) { return y(d.noOfStudents); })
.attr("r", 30)
.text(function (d) { return d.noOfStudents; });
And change your band scale for a point scale:
var x = d3.scalePoint()
.range([0, width])
.padding(0.4);
Here is a fiddle: https://jsfiddle.net/kks4gcL3/
I've modified nice AlainRo’s Block for my needs (unfortunately can't link to it, because have not enough reputation), and I can't remove old data chart after entering new data. There is my codepen. In another example I've added merge(), and the chart is well aligned but the old one is still visible and text values are missed.
I spent a lot of time on it, and I run out of ideas.
There's code
barData = [
{ index: _.uniqueId(), value: _.random(1, 20) },
{ index: _.uniqueId(), value: _.random(1, 20) },
{ index: _.uniqueId(), value: _.random(1, 20) }
];
var margin = {top: 20, right: 20, bottom: 50, left: 70},
width = 400 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom,
delim = 4;
var scale = d3.scaleLinear()
.domain([0, 21])
.rangeRound([height, 0]);
var x = d3.scaleLinear()
.domain([0, barData.length])
.rangeRound([0, width]);
var y = d3.scaleLinear()
.domain([0, 21])
.rangeRound([height, 0]);
var svg = d3.select('#chart')
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append('g')
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
svg.append("g")
.call(d3.axisLeft(y));
function draw() {
x.domain([0, barData.length]);
var brush = d3.brushY()
.extent(function (d, i) {
return [[x(i)+ delim/2, 0],
[x(i) + x(1) - delim/2, height]];})
.on("brush", brushmove);
var svgbrush = svg.selectAll('.brush')
.data(barData)
.enter()
.append('g')
.attr('class', 'brush')
.append('g')
.call(brush)
.call(brush.move, function (d){return [d.value, 0].map(scale);});
svgbrush
.append('text')
.attr('y', function (d){return scale(d.value) + 25;})
.attr('x', function (d, i){return x(i) + x(0.5);})
.attr('dx', '-.60em')
.attr('dy', -5)
.style('fill', 'white')
.text(function (d) {return d3.format('.2')(d.value);});
svgbrush
.exit()
.append('g')
.attr('class', 'brush')
.remove();
function brushmove() {
if (!d3.event.sourceEvent) return; // Only transition after input.
if (!d3.event.selection) return; // Ignore empty selections.
if (d3.event.sourceEvent.type === "brush") return;
var d0 = d3.event.selection.map(scale.invert);
var d = d3.select(this).select('.selection');;
var d1 =[d0[0], 0];
d.datum().value = d0[0]; // Change the value of the original data
d3.select(this).call(d3.event.target.move, d1.map(scale));
svgbrush
.selectAll('text')
.attr('y', function (d){return scale(d.value) + 25;})
.text(function (d) {return d3.format('.2')(d.value);});
}
}
draw();
function upadateChartData() {
var newBarsToAdd = document.getElementById('charBarsCount').value;
var newBarData = function() {
return { index: _.uniqueId(), value: _.random(1, 20) }
};
newBarData = _.times(newBarsToAdd, newBarData);
barData = _.concat(barData, newBarData)
draw();
};
Is it also possible to remove cross pointer and leave only resize, when I'm dragging top bar border?
You're appending g elements twice. This:
svgbrush.enter()
.append('g')
.attr('class', 'brush')
.merge(svgbrush)
.append('g')
.call(brush)
.call(brush.move, function (d){return [d.value, 0].map(scale);});
Should be:
svgbrush.enter()
.append('g')
.attr('class', 'brush')
.merge(svgbrush)
.call(brush)
.call(brush.move, function (d){return [d.value, 0].map(scale);});
Here is your updated Pen: http://codepen.io/anon/pen/VmavyX
PS: I also made other changes, declaring some new variables, just to organize your enter and update selections and solving the texts problem.
I have data like the following
date,values
2016-10-01,10
2016-10-02,20
2016-10-03,30
2016-10-04,5
2016-10-05,50
2016-10-06,2
2016-10-07,7
2016-10-08,17
and am generating a bar chart using the following code
var margin = {top: 20, right: 20, bottom: 70, left: 40},
width = 800 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var parseDate = d3.timeParse("%Y-%m-%d");
var x = d3.scaleBand().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var xAxis = d3.axisBottom(x);
var yAxis = d3.axisLeft(y);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "<strong>Month of " + d.date + ":</strong> <span style='color:red'>" + d.value + " sales</span>";
})
var svg = d3.select("#barg").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.call(tip);
data = d3.csvParse(d3.select("pre#data2").text());
data.forEach(function(d) {
d.date = parseDate(d.date);
d.value = +d.value;
});
x.domain(data.map(function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.value; })]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", "-.55em")
.attr("transform", "rotate(-90)" )
svg.append("g")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Value ($)");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.date); })
.attr("width", x.bandwidth() - 5)
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
So the problem I am having is that I have ordinal data, but for large cardinality (for instance, 120 data points) The x axis has way too many ticks. I have tried a few things like tickValues, but when I use this, my x axis tick points all show up on top of each other. Ideally I would like 10 tick points or so, when the cardinality is high. Any ideas?
This can be done using tickValues indeed. For instance, in this demo, we have 200 values, so the axis is absolutely crowded:
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 100);
var data = d3.range(200);
var xScale = d3.scaleBand()
.domain(data.map(function(d){ return d}))
.range([10, 490]);
var xAxis = d3.axisBottom(xScale);
var gX = svg.append("g").call(xAxis);
<script src="https://d3js.org/d3.v4.min.js"></script>
Now, the same code using tickValues:
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 100);
var data = d3.range(200);
var xScale = d3.scaleBand()
.domain(data.map(function(d){ return d}))
.range([10, 490]);
var xAxis = d3.axisBottom(xScale)
.tickValues(xScale.domain().filter(function(d,i){ return !(i%10)}));
var gX = svg.append("g").call(xAxis);
<script src="https://d3js.org/d3.v4.min.js"></script>
In this last snippet, tickValues uses the remainder operator to show only 1 in every 10 ticks:
.tickValues(xScale.domain().filter(function(d,i){
return !(i%10)
}));
Here is a general solution to this problem using tickFormat(...). We can define a minimum acceptable width for our ticks, then skip every nth tick based on this minimum.
d3
.axisBottom(xScale)
.tickFormat((t, i) => {
const MIN_WIDTH = 30;
let skip = Math.round(MIN_WIDTH * data.length / chartWidth);
skip = Math.max(1, skip);
return (i % skip === 0) ? t : null;
});
let skip = ... is a rearrangement of the inequality ChartWidth / (NumTicks / N) > MinWidth. Here N represents the tick "step size", so we are asserting that the width of every nth tick is greater than the minimum acceptable width. If we rearrange the inequality to solve for N, we can determine how many ticks to skip to achieve our desired width.
i'm trying to generate multiple charts into multiple divs, as i try to duplicate the barchart in another div , the second barchart goes out of position and generates the chart at random location
i have posted js in two script tags
<script>
function intermediate(selected){
console.log(selected);
d3.select("svg").remove();
var metric = selected;
console.log(metric);
var dataFile = metric + '.csv';
d3.csv(dataFile,function(data){
console.log(data);
updateData(data);
});
}
var dataFile="SP_Sterling.csv";
d3.csv(dataFile,function(data){
// console.log(data);
updateData(data);
})
function updateData(data){
var margin = {top: 20, right: 20, bottom: 30, left: 80},
padding = {top: 60, right: 60, bottom: 60, left: 60},
width = 860 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("#groupedbarchart").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 + ")");
// Update the bar chart
//i'm trying to Update the bar chart based on array objects and it seems that my bar is not getting refreshed
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var x1 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.ordinal()
.range(["#00a65a", "#f56954"]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d,i) {
return "<strong>Count:</strong> <span style='color:red';>" + d.value + "</span>";
});
var monthvalues = d3.keys(data[0]).filter(function(key) { return key !== "Month"; });
data.forEach(function(d) {
d.monthdata = monthvalues.map(function(name) { return {name: name, value: +d[name]}; });
});
x0.domain(data.map(function(d) { return d.Month; }));
x1.domain(monthvalues).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(d) { return d3.max(d.monthdata, function(d) { return d.value; }); })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Count");
svg.call(tip);
//enter
var bar = svg.selectAll(".bar")
.data(data);
bar.enter()
.append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x0(d.Month) + ",0)"; });
//update()
bar.selectAll("rect")
.data(function(d) { return d.monthdata; })
.enter()
.append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
.style("fill", function(d) { return color(d.name); });
//remove()
var legend = svg.selectAll(".legend")
.data(monthvalues.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color)
.append("rect");
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
}
</script>
<script>
function longrunning(selected){
console.log(selected);
d3.select("svg").remove();
var metric = selected;
console.log(metric);
var dataFile1 = metric +'_long' + '.csv';
console.log(dataFile1);
d3.csv(dataFile1,function(data){
console.log(data);
updateData(data);
});
}
var dataFile1="SP_Sterling_long.csv";
d3.csv(dataFile1,function(data){
// console.log(data);
updateData(data);
})
function updateData(data){
var margin = {top: 20, right: 20, bottom: 30, left: 80},
padding = {top: 60, right: 60, bottom: 60, left: 60},
width = 860 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("#barchart").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 + ")");
// Update the bar chart
//i'm trying to Update the bar chart based on array objects and it seems that my bar is not getting refreshed
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var x1 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.ordinal()
.range(["#00a65a", "#f56954"]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d,i) {
return "<strong>Count:</strong> <span style='color:red';>" + d.value + "</span>";
});
var monthvalues = d3.keys(data[0]).filter(function(key) { return key !== "Month"; });
data.forEach(function(d) {
d.monthdata = monthvalues.map(function(name) { return {name: name, value: +d[name]}; });
});
x0.domain(data.map(function(d) { return d.Month; }));
x1.domain(monthvalues).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(d) { return d3.max(d.monthdata, function(d) { return d.value; }); })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Count");
svg.call(tip);
//enter
var bar = svg.selectAll("barchart")
.data(data);
bar.enter()
.append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x0(d.Month) + ",0)"; });
//update()
bar.selectAll("rect")
.data(function(d) { return d.monthdata; })
.enter()
.append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
.style("fill", function(d) { return color(d.name); });
//remove()
var legend = svg.selectAll(".legend")
.data(monthvalues.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color)
.append("rect");
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
}
</script>
<div class="groupedbarchart;visible-*-block" id="groupedbarchart" style="height: 600px;border: red 2px solid;">
<select class="selectpicker" data-live-search="false" data-size="7">
<option>SP_Sterling</option>
<option>IWH</option>
<option>IWH_BreakFix</option>
</select>
</div>
<div class="barchart;visible-*-block" id="barchart" style="height: 500px; border:red solid 2px;">
<select class="longrunning" data-live-search="false" data-size="7">
<option>SP_Sterling</option>
<option>IWH</option>
<option>IWH_BreakFix</option>
</select>
</div>
Ok, so I fixed it so you can have multiple barcharts which different id attributes. They will have the same functionality. I am sorry to say, but I really hate the jsbin editor, as it seems to very crowded and not really easy to use. Therefor, i have made a plunker, just so I could faster figure out your code. You can find it here.
Let me explain what I did:
First, i added the functionality of the select box in your html to another barchart container. Here I added the select to the div with id "bar-chart":
<div class="box-body chart-responsive">
<div class="chart" id="bar-chart" style="height: 500px;">
<select class="selectpicker" data-live-search="false" data-size="7">
<option>SP_Sterling</option>
<option>IWH</option>
<option>IWH_BreakFix</option>
</select>
</div>
</div>
Then I changed the calling function at the end of your html, the one where you build charts on the change events:
$('.selectpicker').on('change', function(){
var parent = $(this).parent();
console.log(parent);
var selected = $(this).find("option:selected").val();
//alert(selected);
intermediate(selected, parent);
});
As you can see, I am looking for the parent here (the parent of each select picker is the div to which you want to append your chart, I noticed). I pass that element as parameter to your intermediate function.
Then as last, I have changed the intermediate function. I will only show the beginning, as that is where i did my changes:
function intermediate(data, element){
d3.select("svg").remove();
var newData=[
{
"Month": "Feb",
"Success_Count": 49,
"Failure_Count": 20
},
{
"Month": "Jan",
"Success_Count": 35,
"Failure_Count": 3
}
];
updateData(newData, element);
}
function updateData(data, element){
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 760 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var selection = d3.select(element);
console.log("d3 selection", element[0]);
var svg = d3.select(element[0]).append("svg") // THIS IS VERY IMPORTANT!!
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
So basically, I have added a new parameter to your functions (the one which will pass the parent element). Then I also cleaned up your "old data". For this example, you don't need it.
Then, and this is the most important part, I have changed the d3 selection. The plunk works, if you have more questions, shoot! :-)
************* EDIT ****************
I did notice that the charts do not really update the way they should and if you change one barchart, the other one disappears. I have fixed that now. The plunker code has been update (the link should still be the same).
What have I changed:
d3.select("svg").remove();
This has been removed from the code. You don't need it.
Then, I also had to change the update data function:
function updateData(data, element){
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 760 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg;
//check if there already is an svg element
if(d3.select(element[0]).select("svg").empty()) {
svg = d3.select(element[0]).append("svg") // THIS IS VERY IMPORTANT!!
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
As you can see, it now checks if there is already an svg. If so, it just updates the data and the graph if necessary. You also need this:
...
else {
svg = d3.select(element[0]).select("svg");
}
in case there already is an svg element. The graph and its axes is created entirely in that first "if" statement.
This whole thing of enter selections, updating and the exit selection might look very complicated. I have written about it in a previous post, which you can find here. If you have more questions, please let me know!
I try to make a bar chart on the basis of 2D data array (I din`t want to use 2D array initially, so there is a function "mergingAr", which merges them) using d3.js. Here is the code:
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
var arr1 = [399200,100000, 352108, 600150, 39000, 17005, 4278];
var arr2 = [839, 149, 146, 200, 200, 121, 63];
function mergingAr (array1, array2)
{
var i, out = [];//literal new array
for(i=0;i<array1.length;i++)
{
out.push([array1[i],array2[i]]);
}
return out;
}
var data = mergingAr(arr1, arr2);
margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, d3.max(data, function(d) {
return d[0]; })])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[1]; })])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d[0]); })
//.attr("width", x.rangeBand())
.attr("width", width/a1.length)
.attr("y", function(d) { return y(d[1]); })
.attr("height", function(d) { return height - y(d[1]); });
Te problem is - the bars cover each other, there are no distance between them, even if I used rangeRoundBands.
There are 2 issues in your code.
The first one is that the data array is not sorted. In order to sort it you can do:
out = out.sort(function(a,b) { return d3.ascending(a[0],b[0]) })
before returning out in your mergeAt function. Sorting the array makes sure that you process bars in the right order.
The second issue is that your intervals are not equal. To remediate to this, I made the width of a block equal to the distance to the next one (but you might want to do something different):
.attr("width", function(d,i){
if(i!=(data.length-1)) {
return x(data[i+1][0])-x(data[i][0])
} else {
return 10; // the last block is of width 10. a cleaner way is to add a
// marker at the end of the array to know where to finish
// the axis
}
})
JsFiddle: http://jsfiddle.net/chrisJamesC/6WJPA/
Edit
In order to have the same interval between each bar and the same width, you have to change the scale to an ordinal one:
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1)
.domain(data.map(function(d){return d[0]}))
Then, you need to change the way you compute the width to:
.attr("width", x.rangeBand())
JsFiddle: http://jsfiddle.net/chrisJamesC/6WJPA/2/