Here is the JSFiddle
please look at the function drawBarchart();
Note: in my example when xData values are renamed and made unique all 4 bars are shown, but omitted when values are same, i know this is expected behavior but i have to allow repeated values.Please help..
code:
$(document).ready(function(){
var dataArray = [
{
"xData" : "Repeat",
"yData" : 38
},
{
"xData" : "Unique",
"yData" : 27
},
{
"xData" : "Repeat",
"yData" : 27
},
{
"xData" : "Repeat",
"yData" : 29
} ];
drawBarchart("graph",dataArray,"count",700,400);
}
);
function drawBarchart(containerId, dataArray, yAxisText, chartAreaWidth,
chartAreaHeight) {
var margin = {
top : 20,
right : 20,
bottom : 30,
left : 40
}, width = chartAreaWidth - margin.left - margin.right, height = chartAreaHeight
- margin.top - margin.bottom;
var formatPercent = d3.format(".0%");
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").tickFormat(formatPercent);
var yAxis = d3.svg.axis().scale(y).orient("left");
var svg = d3.select("#" + containerId).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(dataArray.map(function(d) {
return d.xData;
}));
y.domain([ 0, d3.max(dataArray, function(d) {
return d.yData;
}) ]);
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(yAxisText);
svg.selectAll(".bar").data(dataArray).enter().append("rect")
.attr("class", "bar").attr("x", function(d) {
return x(d.xData);
}).attr("width", x.rangeBand()).attr("y", function(d) {
return y(d.yData);
}).attr("height", function(d) {
return height - y(d.yData);
});
function type(d) {
d.yData = +d.yData;
return d;
}
}