Skip to content Skip to sidebar Skip to footer

D3 X Axis Text And Tick Line Not Visible

I'm having an issue with a D3 chart where my x axis text and tick lines are invisible. I can see both elements placed properly in web inspector on the chart, and I have stroke and

Solution 1:

Use the height/width that includes the subtracted margin values.

var height = svgHeight - margin.top - margin.bottom;
var width = svgWidth - margin.left - margin.right;

var svg = d3.select('svgContainer')
.append('svg')
.attr('width', width)
.attr('height', height)
.attr('transform, 'translate(' + margin.left + ',' + margin.top + ')');

Solution 2:

If you look at the documentation, you're gonna see:

Regardless of orientation, axes are always rendered at the origin.

So, your axis is there, but on the very top of the SVG, and you can't see it.

Solution: You have to translate it down:

svg.append('g')
    .attr('class', 'xAxis')
    .attr("transform", "translate(0," + margin.top + ")")
    .call(xAxis);

Here is a demo with your(*) code:

var margin = {top: 40, right: 20, bottom: 20, left: 20};
var svgWidth = 500;
var svgHeight = 200;
var height = svgHeight - margin.top - margin.bottom;
var width = svgWidth - margin.left - margin.right;

var svg = d3.select('body')
.append('svg')
.attr('width', svgWidth)
.attr('height', svgHeight)
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

var x = d3.scale.linear()
	.range([0, width]);

 var xAxis = d3.svg.axis()
.scale(x)
.orient('top')
.innerTickSize(-height);

 svg.append('g')
.attr('class', 'xAxis')
.attr("transform", "translate(0," + margin.top + ")")
.call(xAxis);
path, line {
	fill: none;
	stroke: black;
	shape-rendering: crispEdges;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

*: your code is full of problems, from undefined variables and properties to missing quotes. I suggest you revise it. Besides that, there is no point in translating an SVG (which doesn't work), that part of the code requires a group instead.

Post a Comment for "D3 X Axis Text And Tick Line Not Visible"