d3:scaleTime

by Richard Hunter

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>

CSS

svg {
  background: #fff1e5;
}

JavaScript

const formatMonth = d3.utcFormat('%m-%y');
const formatYear = d3.utcFormat('%Y');

const formatTime = (date) => {
  if (date.getMonth() === 0) {
    return formatYear(date);
  } else {
    return formatMonth(date);
  }
}

const margins = {
  top: 40,
  bottom: 40,
  left: 20,
  right: 10,
};

const width = 700;
const height = 400;

const xScale = d3.scaleTime()
  .domain([new Date(2020, 0, 23), new Date(2024, 7, 2)])
  .range([margins.left, width - margins.right])

const svg = renderSVG(width, height);
const xAxis = createXAxis(xScale);
renderXAxis(svg, xAxis);

function renderSVG(width, height) {
  return d3.select('body')
    .append('svg')
    .attr('width', width)
    .attr('height', height);
}

function createXAxis(xScale) {
  return d3.axisBottom()
    .scale(xScale)
    .ticks(10)
    .tickSizeInner(3)
    .tickSizeOuter(0)
   // .offset(-20)
    .tickFormat(formatTime);
}

function renderXAxis(svg, xAxis) {
  svg.append('g')
    .attr('transform', `translate(0, ${height - margins.bottom})`)
    .call(xAxis);
}