Here is a link to a d3 js graph.
http://enjalot.com/inlet/4131006/
And here is the code
var w = 300,
h = 300,
padding = 31,
p = 10;
var data = [{count:200,year:2008},
{count:240,year:2010},
{count:290,year:2009}];
var bar_height = d3.scale.linear()
.domain(d3.extent(data, function(d) { return d.count; }) ) // min max of count
.range([p,h-p]); // min max of area to plot in
var bar_xpos = d3.scale.linear()
.domain(d3.extent(data, function(d) { return d.year; }) ) // min max of year
.range([p,w-p]); // min max of area to plot in
var xAxis = d3.svg.axis()
.scale(bar_xpos)
.orient("bottom")
.ticks(5); //Set rough # of ticks
var yAxis = d3.svg.axis()
.scale(bar_height)
.orient("left")
.ticks(5);
var svg = d3.select("svg")
.attr("width", w)
.attr("height", h);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
svg.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("x", function(d) {
return bar_xpos(d.year); })
.attr("y", function(d) {
return h - bar_height(d.count); })
.attr("width", 10)
.attr("height", function(d) {return bar_height(d.count); })
.attr("fill", "steelblue")
I have been able to draw y axis and x axis to this graph but they do not look correct.There are some issue
The rectangle line in not on the X axis.
There is no 0 on x axis and y axis on the graph.It starts with the min value from the json data.And is dere any way to configure the distance between two marks on the axis.
To configure your axes, you have to modify your scales.
d3.extent() returns the min and max of your data simultaneously and use that as the domain of your graph. Because you use
bar_heightandbar_xposto format yourscales, the minimum values for the scales will also be the minimum values from the data. To fix this, used3.max()instead, like so:You can use 0 for your bar_xpos min, but it doesn’t make sense if you are going by year because your data will be impossible to actually read. I used 2000 for the min here.
Working example here.
Also, in this example I formatted your bar location to line up a bit nicer with the axes. I replaced
.attr('width', 10)with.attr('width', barwidth), and subtractedbarwidthfrom thexattr as well. This will make the right edge of your bar line up with the right edge of the axis instead of spill over the edge.Edit:
Modified the
yandheightattributes. The height was going the opposite way, under the graph otherwise. Link has been updated.