Reputation: 339
I’m working on a bar chart using d3.js (v5), and I’m running into some trouble getting the xAxis ticks to appear. Relevant code is as follows, full repo is at (https://github.com/dylanesque/BarChart):
const dateParser = d3.timeParse('%Y');
const xAccessor = (d) => dateParser(d[0]);
const xScale = d3
.scaleTime()
.domain(d3.extent(dataset, xAccessor))
.range([0, dimensions.boundedWidth]);
const xAxisGenerator = d3.axisBottom().scale(xScale).ticks(14);
const xAxis = bounds
.append('g')
.call(xAxisGenerator)
.attr('id', 'x-axis')
.style('transform', `translateY(${dimensions.boundedHeight}px)`);
const xAxisLabel = xAxis
.append('text')
.attr('x', dimensions.boundedWidth / 2)
.attr('y', dimensions.margin.bottom - 10)
.attr('fill', 'black')
.style('font-size', '1.4em');
What's strange about this is that I'm using the same basic approach on another d3 project I'm working on (https://github.com/dylanesque/Scatter), and it's working as expected there.
Upvotes: 1
Views: 554
Reputation: 339
The problem was that this line:
const parseTime = d3.timeParse('%Y');
needed to be this line:
const parseTime = d3.timeParse('%Y-%m-%d');
From the d3.js time-format
docs:
Parsing is strict: if the specified string does not exactly match the associated specifier, this method returns null. For example, if the associated specifier is %Y-%m-%dT%H:%M:%SZ, then the string "2011-07-01T19:15:28Z" will be parsed as expected, but "2011-07-01T19:15:28", "2011-07-01 19:15:28" and "2011-07-01" will return null.
Upvotes: 1
Reputation: 495
It is because you have no text()
specified, your other codes in github all have the text()
entry except the xAxisLabel
const xAxisLabel = xAxis
.append('text')
.attr('x', dimensions.boundedWidth / 2)
.attr('y', dimensions.margin.bottom - 10)
.attr('fill', 'black')
.style('font-size', '1.4em')
.text("WHAT"); // the text to show
Upvotes: 0