How do I make a basic column(vertical) chart in d3js? - javascript

I'm trying out d3js and I have a problem with getting my first basic column(vertical bar) chart work. The only thing I find a bit difficult to understand is the scaling thing. I want to make the x and y axis ticks with labels but I have the following problems:
First of all here is my data:
{
"regions":
["Federal","Tigray","Afar","Amhara","Oromia","Gambella","Addis Ababa","Dire Dawa","Harar","Benishangul-Gumuz","Somali","SNNPR "],
"institutions":
[0,0,34,421,738,0,218,22,22,109,0,456]
}
On the y-axis the values are there but the order is reversed. Here is the code:
var y = d3.scale.linear().domain([0, d3.max(data.institutions)]).range([0, height]);
then I use this scale to create a y-axis:
var yAxis = d3.svg.axis().scale(y).orient("left");
and add this axis to the svg element
svgContainer.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("Institutions");
the problem here is that the y-axis start from 0 at the top and with 700 at the bottom which is OK but it should be in reverse order.
The other problem I have it the x-axis. I want to have an ordinal scale since the values I want to put are in the regions names I have above. So here's what I've done.
var x = d3.scale.ordinal()
.domain(data.regions.map(function(d) { return d.substring(0, 2); }))
.rangeRoundBands([0, width], .1);
then the axis
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
and finally add it to the svg element
svgContainer.append("g")
.attr("class", "x axis")
.attr("transform", "translate( 0," + height + ")")
.call(xAxis);
Here the problem is the ticks as well as the labels appear but they are not spaced out evenly and do not correspond with the center of the rectangles I'm drawing. Here is the complete code so you can see what's happening.
$(document).ready(function(){
d3.json("institutions.json", draw);
});
function draw(data){
var margin = {"top": 10, "right": 10, "bottom": 30, "left": 50}, width = 700, height = 300;
var x = d3.scale.ordinal()
.domain(data.regions.map(function(d) { return d.substring(0, 2); }))
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.domain([0, d3.max(data.institutions)])
.range([0, height]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var svgContainer = d3.select("div.container").append("svg")
.attr("class", "chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" +margin.left+ "," +margin.right+ ")");
svgContainer.append("g")
.attr("class", "x axis")
.attr("transform", "translate( 0," + height + ")")
.call(xAxis);
svgContainer.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("Institutions");
svgContainer.selectAll(".bar")
.data(data.institutions)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d, i) {return i* 41;})
.attr("y", function(d){return height - y(d);})
.attr("width", x.rangeBand())
.attr("height", function(d){return y(d);});
}

I put the code to Fiddle: http://jsfiddle.net/GmhCr/4/
Feel free to edit it! I already fixed both problems.
To fix the upside-down y-axis just swap the values of the range function arguments:
var y = d3.scale.linear().domain([0, d3.max(data.institutions)]).range([height, 0]);
Do not forget to adjust the code for the bars if you change the scale!
The source of the mismatch between bars and the x-axis can be found here:
var x = d3.scale.ordinal()
.domain(data.regions.map(function(d) {
return d.substring(0, 2);}))
.rangeRoundBands([0, width], .1);
svgContainer.selectAll(".bar")
.data(data.institutions)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d, i) {return i* 41;})
.attr("y", function(d){return height - y(d);})
.attr("width", x.rangeBand())
.attr("height", function(d){return y(d);});
You specify the padding for rangeRoundBands at 0.1 but you ignore the padding when computing the x and width values for the bars. This for example is correct with a padding of 0:
var x = d3.scale.ordinal()
.domain(data.regions.map(function(d) {
return d.substring(0, 2);}))
.rangeRoundBands([0, width], 0);
svgContainer.selectAll(".bar").data(data.institutions).enter().append("rect")
.attr("class", "bar")
.attr("x", function(d, i) {
return i * x.rangeBand();
})
.attr("y", function(d) {
return y(d);
})
.attr("width", function(){
return x.rangeBand();
})
.attr("height", function(d) {
return height -y(d);
});
The padding determines how much of the domain is reserved for padding. When using a width of 700 and a padding of 0.1 exactly 70 pixels are used for padding. This means you have to add 70 / data["regions"].length pixels to every bar's x value to make this work with a padding.

Related

Filter with d3.js

I have a big problem.
I use d3 to visualize my (poll)data. (So Questions and answers) It works fine except one problem.
Sometimes it doesn't visualize the data like they are. For example one time d3 get all right data about d3.json. But the graph is not right. It should load 300 answers in the first bars but it just show 50. I tested it and the json works.
I tried to filter the graph and I got the same problem.
This is my d3 code.
<div>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
var margin = {
top: 20,
right: 30,
bottom: 30,
left: 430
},
width = 1400 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var xScale = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var yScale = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(10);
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("class", "chart");
var chart = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("getdata.php", function(error, data) {
xScale.domain(data.map(function(d) {
return d.text;
}));
yScale.domain([0, d3.max(data, function(d) {
return d.count;
})]);
chart.selectAll(".bar")
.data(data)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d) {
return xScale(d.text);
})
.attr("y", function(d) {
return yScale(d.count);
})
.attr("height", function(d) {
return height - yScale(d.count);
})
.attr("width", xScale.rangeBand())
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart.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("Antworten");
});
function type(d) {
d.count = +d.text;
return d;
}
</script>
</div>
I guess the problem starts here. But I don't know why. The problem doesn't appear at every question. Only at a few or when I try to use my filter.
Maybe it happens when two values have a big difference?
Update:
It is like: D3 doesn't want to lose the smallest bar. So other bars must based on that smallest. And then the values are not correct for the bigger bars. Maybe the Y scale depends on the smallest bar.

Multiple Bar charts with fixed y-axis to highlight the different as shown in fig

I looking any chart library which has configuration for custom y-axis values. I want to customize the y-axis like ( 0 to 3). I seen D3 and other chart libraries, the Y-axis automatically generates the values. I my design there is only one filed and on one for compare on the x-axis.
Which chart library is most suited for this condition to make this happen. If any example already on google, please share...
If you are looking for a D3 solution then you can refer my fiddle below:
http://jsfiddle.net/cyril123/7ftuumv4/2/
code:
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
//specify data here
data = [{letter: "1", value: 1.3}]
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.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 + ")");
//as you have a fixed x axis value and single data
x.domain([data[0].letter]);
//as you have a fixed range for y axis
y.domain([0, 3]);
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("Value");
//make the bar chart
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.letter); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); });

Stop bars from centering in chart

I am creating a bar chart using d3. To do so I looked at this code and changed it a little bit.
However what it does is centering the bars, and I would like the bars to start immediate at the bar y axis.
It looks like the issue comes from these 2 pieces of code:
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .0);
and the last line of this one:
svg.selectAll(".bar")
.data(graphObj)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.step); })
where the x(d.step) is responsible for the distance, the x is set at the var x = ...
Somehow I need to change this, but cant figure it out.
The distance is a bit different since I changed this:
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
to this:
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .0);
but it doesn't help much.
Can you help out here?
This is my code:
$('#chartDiv').html('');
var margin = {top: 10, right: 10, bottom: 35, left: 50},
width = 600 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .0);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10, "");
var svg = d3.select("#chartDiv").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 + ")");
graphObj.forEach(function(d) {
d.step = +d.step;
d.temp = +d.temp;
});
x.domain(graphObj.map(function(d) { return d.step; }));
y.domain([0, d3.max(graphObj, function(d) { return d.temp; })]);
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", "-40px")
.style("text-anchor", "end")
.text("Temperature");
svg.selectAll(".bar")
.data(graphObj)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { console.log(d.step, x.rangeBand(), x(d.step)); return x(d.step); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.temp); })
.attr("height", function(d) { return height - y(d.temp); });
if ($('#chartDiv').css('left').replace('px','') < 0) {
$('#chartDiv').animate({
left: 10
}, 1000);
}
you need to add the i variable to the .attr("x", function(d) { return x(d.step); }), like so: .attr("x", function(d, i) { return x.rangeRoundBands() * i; }), so it will go through the bars and place them one after the other (this might need some tweaking, can't do it properly without a jsfiddle) but should at least get you on the path of fixing it without issues

Error parsing d3 line chart JSON data

Having issues with getting JSON data on a line chart, i can do this for a bar chart totally fine but for some reason it gives me an error when doing a line chart. There isn't much documentation around so see if anyone knows.
I get this error
Error: Problem parsing d="MNaN,400LNaN,258.65447419986936LNaN,221.90289571086436LNaN,183.32244720226433LNaN,134.29131286740693LNaN,149.70607446113652LNaN,63.1395602003048LNaN,37.44829087742215LNaN,69.40997169605924LNaN,0LNaN,169.91073372523405LNaN,643.2397126061397"
JSON data is as follows:
[{"logins":"3333","month_name":"January"},{"logins":"4956","month_name":"February"},{"logins":"5378","month_name":"March"},{"logins":"5821","month_name":"April"},{"logins":"6384","month_name":"May"},{"logins":"6207","month_name":"June"},{"logins":"7201","month_name":"July"},{"logins":"7496","month_name":"August"},{"logins":"7129","month_name":"September"},{"logins":"7926","month_name":"October"},{"logins":"5975","month_name":"November"},{"logins":"540","month_name":"December"}]
Now the code:
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = $("svg").parent().width();
height = $("svg").parent().height();
aspect = 500 / 950;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.month_name); })
.y(function(d) { return y(d.logins); });
var svg = d3.select(document.createElement("div")).append("svg")
.attr("preserveAspectRatio", "xMidYMid")
.attr("viewBox", "0 0 950 500")
.attr("width", width)
.attr("height", width * aspect)
.attr("id", "art_chart")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(d3.extent(data, function(d) { return d.month_name; }));
y.domain(d3.extent(data, function(d) { return d.logins; }));
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("Logins");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
Anyone know how to fix it so it displays the line chart?
You need to parse your dates and pass in the numbers as numbers:
data.forEach(function(d) {
d.month_name = d3.time.format("%B").parse(d.month_name);
d.logins = +d.logins;
});
If you run this code just after loading the JSON, everything should work fine.

how to use d3 .ticks to show original y-axis values in bar chart

I have some number of amount (in dollar) which I am showing on y-axis and year on x-axis. now, I want to show original number on y-axis but not able to do.
i mean on y axis i want to show number from 1 to 100000 as amount but now, with .ticks(10) i can only used between 0 to 8000 amount at y axis.
and one more thing that if i want to show name as string at x axis then how can i show please let me know. i am stuck here and newly with d3.
function test() {
var graph_data;
// in graph_data it should contain value like this
// [Object { letter="2011", frequency="10000"},
// Object { letter="2012", frequency="8200"}]
var 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.ordinal()
.rangeRoundBands([0, 110], .3);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.tickPadding(10)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.tickPadding(3)
.orient("left")
.ticks(10);
var svg = d3.select("#award_by_year_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 + ")");
x.domain(graph_data.map(function(d) { return d.letter; }));
y.domain([0, d3.max(graph_data, function(d) { return d.frequency; })]);
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("Total dollar");
svg.selectAll(".bar")
.data(graph_data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.letter); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); });
function type(d) {
d.frequency = +d.frequency;
return d;
}
}
now, this code is working as below chart image. and i want to change value of y axis according to total dollar value and it's coming from table and it can also -ve as well +ve and upper limit not fixed. then how can resolve.
please give me valuable solution.
thanks
Ok, from what I understand from your question here's what I got:
i mean on y axis i want to show number from 1 to 100000 as amount but
now, with .ticks(10) i can only used between 0 to 8000 amount at y
axis.
For this I would check out https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-tickValues, which documents the function tickValues. With this you can specify exactly what you want to show on the y axis. Say you want to show just 0 and 100000 then you can simply pass the array [0, 10000].
and one more thing that if i want to show name as string at x axis
then how can i show please let me know. i am stuck here and newly with
d3.
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
.selectAll('text')
.text(function(d) {
return 'Some string: ' + d.letter
})
This will let you customize any of the tick values on the x axis. In case I didn't understand the first part of the question, you can also use this trick on the y axis to customize the output of the tick value.

Categories