newcomer newcomer - 1 month ago 7
Javascript Question

Barchart X-Axis is getting hidden when bringing to bottom in D3.js

I ma shifting the X-Axis to bottom, it is not visible and only coming when its on the bar chart. There is some svg area problem which I ma not able to find out. how to shift the barchart a bit upwards so that X=Axis labeling could be accommodated.

Here is the fiddle link Working but X-Axis Label is on the Top

a = 100;
b = 150;
c = 103;
dataset= [a,b,c];
var w = 500;
var h = 250;
var barPadding = 1;
var marginleft = 1;
var margintop =1;
var marginbottom =15;
margin = {top:1, right:10, bottom:1, left:1};
colors = ["#e41a1c", "#377eb8", "#4daf4a"];
h = h ;

var category= ['A', 'B', 'C'];

var x = d3.scale.ordinal()
.rangeRoundBands([0, w]);

var xAxis = d3.svg.axis()

//Create SVG element
var svg ="#hello")
.attr("width", w )
.attr("height", h )
.attr("transform", "translate(" + margin.left + "," + + ")");

.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")



.attr("x", function(d, i) {
return i * (w / dataset.length);
.attr("y", function(d) {
return h - (d*1.5) ;
.attr("width", w / dataset.length - barPadding)
.attr("height", function(d) {
return (d*2 );

.attr("fill", function(d,i) {
return colors[i];
// .attr("fill", function(d) {
// return "rgb(0, 0, " + (d * 10) + ")";

var x_Axis = svg.append('g')
.attr("transform", "translate(0," + (20) + ")")
.style("text-anchor", "start")
.attr("dx", "-2.5em")
.attr("dy", ".5em")
.attr("transform", "rotate(-15)" );


Your code has several problems:

  • two different datasets for the bars;
  • lacks an ordinal scale for positioning the bars (actually, there is one, which you don't use);
  • lacks a linear scale for the bars values;
  • calls xAxis twice, with different translations;

But, for solving the axis problem, you just need to translate it correctly:

 var x_Axis = svg.append('g')
     .attr("transform", "translate(0," + (h- 30) + ")")
    //30 here is the padding from the bottom of the SVG

Here is your fiddle:

The bars are still showing up behind the axis (actually, the bars are going way below the end of the SVG itself). To fix that, you'll have to draw the bars properly (with a scale setting the range and the domains).