newcomer - 1 year ago 68

Javascript Question

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()

.domain(category)

.rangeRoundBands([0, w]);

var xAxis = d3.svg.axis()

.scale(x)

.orient("bottom")

.ticks(0);;

//Create SVG element

var svg = d3.select("#hello")

.append("svg")

.attr("width", w )

.attr("height", h )

.append("g")

.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")

.attr("class", "x axis")

.attr("transform", "translate(0," + h + ")")

.call(xAxis);

// GENERATING RECTANGLES AND MAKING BAR CHART

svg.selectAll("rect")

.data(dataset)

.enter()

.append("rect")

.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('class','xnewaxis')

.attr("transform", "translate(0," + (20) + ")")

.call(xAxis)

.selectAll("text")

.style("text-anchor", "start")

.attr("dx", "-2.5em")

.attr("dy", ".5em")

.attr("transform", "rotate(-15)" );

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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('class','xnewaxis')
.attr("transform", "translate(0," + (h- 30) + ")")
//30 here is the padding from the bottom of the SVG
```

Here is your fiddle: https://jsfiddle.net/gfwo0br9/

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).

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**