After creating a bar plot, I noticed that my Y axis is reversed and the scale seems off. I've been struggling to figure it out on my own. Here's a link to the Jsfiddle with the code.
If you want to give it a shot somewhere else, here is the code:
var w = 700;
var h = 400;
var margin = 40;
var dataset = [
{key:1,value:4000},
{key:2,value:3500},
{key:3,value:4400},
{key:4,value:3250},
{key:5,value:4785},
{key:6,value:3600},
{key:7,value:3200}
];
var key = function(d) {
return d.key;
};
var value = function(d) {
return d.value;
};
console.log(dataset);
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var xScale = d3.scale.ordinal()
.domain(d3.range(dataset.length+1))
.rangeRoundBands([40, w], 0.05);
var yScale = d3.scale.linear()
.domain([0, 5000])
.range([0, h-40]);
var x_axis = d3.svg.axis().scale(xScale);
var y_axis = d3.svg.axis().scale(yScale).orient("left");
d3.select("svg")
.append("g")
.attr("class","x axis")
.attr("transform","translate(0,"+(h-margin)+")")
.call(x_axis);
d3.select("svg")
.append("g")
.attr("class","y axis")
.attr("transform","translate("+margin+",0)")
.call(y_axis);
//Create bars
svg.selectAll("rect")
.data(dataset, key)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d.value);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return yScale(d.value)-margin;
})
.attr("fill", function(d) {
return "rgb(96, 0, " + (d.value * 10) + ")";
})
//Tooltip
.on("mouseover", function(d) {
//Get this bar's x/y values, then augment for the tooltip
var xPosition = parseFloat(d3.select(this).attr("x")) + xScale.rangeBand() / 2;
var yPosition = parseFloat(d3.select(this).attr("y")) + 14;
//Update Tooltip Position & value
d3.select("#tooltip")
.style("left", xPosition + "px")
.style("top", yPosition + "px")
.select("#value")
.text(d.value);
d3.select("#tooltip").classed("hidden", false)
})
.on("mouseout", function() {
//Remove the tooltip
d3.select("#tooltip").classed("hidden", true);
}) ;
//Create labels
svg.selectAll("text")
.data(dataset, key)
.enter()
.append("text")
.text(function(d) {
return d.value;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d.value) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");