Cannot understand how to use d3.scaleTime()

I’ve completed the Visualize Data with a Bar Chart project and still do not understand how I did it.
I used this code for my x-axis scale, yet the bars and x-axis ticks go beyond the width of the SVG. I thought that .range restricted the data to appear within the values that are set, in this case [0, w]?
d looks like [“1947-07-01”, 250.1], so d[0] is 1947-07-01

const w = 800; 
const xScale = d3.scaleTime()
    .domain(
      [
        new Date(d3.min(data, (d) => d[0])),
        new Date(d3.max(data, (d) => d[0]))
      ]
    )
    .range([0, w])

Hi @Sonnerz, could you post a link to your CodePen? Would make it easier to help.

https://codepen.io/sonnerz/pen/qzmmrp

In the end I had to adjust the width value to make my data fit the axis, but it’s not really how it should be done.
I shouldn’t have to keep adjusting a value to make it fit e.g. 788
The width was set to 800, so I have no idea why subtracting 12 made the graph fit.

const xScale = d3.scaleTime()
    .domain(
      [
        new Date(d3.min(data, (d) => d[0])),
        new Date(d3.max(data, (d) => d[0]))
      ]
    )
    .range([padding, 788])

Hi, see fork. The following is what I did to fix the issue:

 // XSCALE
  const xScale = d3.scaleTime()
    .domain(
      [
        new Date(d3.min(data, (d) => d[0])),
        new Date(d3.max(data, (d) => d[0]))
      ]
    )
    .range([padding, w])
  // main change below
  const barWidth = (w - padding) / data.length;

You were originally passing in the xScaled version of data.length… which I’m not really sure what that gives you, but conceptually, what the bar width should be is the horizontal axis length divided by the number of bars.

Hope this helps :slight_smile:

1 Like

Thank you @katieyang for responding. It does help :slight_smile:
I seem to be getting really confused with the padding/margin ‘stuff’.

I tried to start the next project with no padding/margins, etc. so that I don’t get confused. But I found myself having to add them to be able to view the chart. So I really need to try and understand it better.