D3 tick marks not appearing with date labels

Hello,

I am attempting to make a date graph on D3. However, the tick marks are not appearing on the x-axis


const App = () => {
const data = React.useMemo(() => {
    return [
      new Date("2022-01-01"),
      new Date("2022-02-01"),
      new Date("2022-03-01"),
      new Date("2022-04-01"),
      new Date("2022-05-01")
    ]
  }, [])
  const svgRef = React.useRef(null);
  const width = 500
  const height = 500
  React.useEffect(() => {
    if (svgRef.current) {
      const svg = d3.select(svgRef.current);
      // Remove all SVG
      svg.selectAll("*").remove();
      // Generate the width and domain of the x and y axis.
      // The x-axis will be 500 px wide with a domain of lowest to highest date.
      const xScale = d3.scaleTime().range([0, width]).domain(d3.extent(data));
      // yScale will be a linear scale from 0 to 500 pixels.
      const yScale = d3.scaleLinear().range([height, 0])
      // Create the x-axis
      svg.append("g")
        .attr("transform", `translate(0,${height})`) // Move x-axis to bottom of graph
        .call(
          d3.axisBottom(xScale) // Generate an axis to place tick marks on.
            .ticks(d3.timeMonth.every(1)) // The ticks will be spaced out every month
            .tickFormat((d, i) => { // The text for each tick will be the month name
              if (d instanceof Date) {
                return d3.timeFormat("%B")(d)
              } else {
                return "" + d
              }
            }))
      // Generate the y-axis, no ticks.
      svg.append("g").call(d3.axisLeft(yScale))
    }
  }, [data])

  return (<svg
        ref={svgRef}
        width={width}
        height={height}
      />)
}

const root = ReactDOM.createRoot(document.querySelector('.container'));
root.render(<App />)

I only get this L-shape, with the x-axis containing no tick marks with month labels.

It’s working but your ticks are pushed off the edge of the SVG. For example if I modify this line adding -30 to height, it will show your scale at the bottom.

svg.append("g")
    .attr("transform", `translate(0,${height-30})`) // Move x-axis to bottom of graph

You can look for other adjustments to make to the placement to keep it within the 500x500px SVG.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.