Home > database >  Date axis labels with d3.js
Date axis labels with d3.js

Time:02-19

The date axis of my d3 line chart contains a mixture of months and weekdays. I just want it to be the months and the day of the month (eg 15 Feb).

chart with weird axis

Does anyone know how to fix this?

Super new to d3.js so excuse me.

Thank you!

//create scales
const yScale = d3.scaleLinear()
    .domain(d3.extent(dataset,  yAccessor))
    .range([dimensions.boundedHeight, 0])


const xScale = d3.scaleTime()
    .domain(d3.extent(dataset, xAccessor))
    .range([0, dimensions.boundedWidth])

// draw data 
const lineGenerator = d3.line()
.x(d => xScale(xAccessor(d)))
.y(d => yScale(yAccessor(d)))

const line = bounds.append("path")
  .attr("d", lineGenerator(dataset))
  .attr("fill", "none")
  .attr("stroke", "#af9358")
  .attr("stroke-width", 2)

//draw peripherals
const yAxisGenerator = d3.axisLeft()
    .scale(yScale)

const yAxis = bounds.append("g")
    .call(yAxisGenerator)

const xAxisGenerator = d3.axisBottom()
    .scale(xScale)

const xAxis = bounds.append("g")
    .call(xAxisGenerator)
      .style("transform", `translateY(${
        dimensions.boundedHeight
      }px)`)

const xAxisLabel = xAxis.append("text")
    .attr("x", dimensions.boundedWidth / 2)
    .attr("y", dimensions.marginBottom -10)
    .attr("fill", "black")
    .style("font-size", "1.4em")
    //.html("Date")
    }
drawLineChart()

CodePudding user response:

Fixed this myself using
.tickFormat(d3.timeFormat ("%d %b")) as a method on the axis function ie

const xAxisGenerator = d3.axisBottom()
    .scale(xScale)
    .tickFormat(d3.timeFormat ("%d %b"))
  • Related