d3 / d3-shape

Graphical primitives for visualization, such as lines and areas.
https://d3js.org/d3-shape
ISC License
2.48k stars 310 forks source link

Curve Natural gets outside the svg #208

Closed oliviercperrier closed 1 year ago

oliviercperrier commented 1 year ago

Hi,

When i use this set of data points:

[
      {
        x: new Date("2023-06-11T04:00:00.390Z").getTime(),
        y: 72000,
      },
      {
        x: new Date("2023-06-10T04:00:00.614Z").getTime(),
        y: 72000,
      },
      {
        x: new Date("2023-06-09T04:00:00.422Z").getTime(),
        y: 67500,
      },
]

I get the following graph:

Screenshot 2023-06-13 at 10 30 50 AM

As you can see the curve is truncated by the parent SVG because the path is getting outside of the SVG.

Is there a way to fix that?

Here is the code i use:

  const height = 150;
  const width = 355;

  const yValues = data.map(item => item.y);
  const xValues = data.map(item => item.x);

  const scaleX = scaleLinear()
    .domain([Math.min(...xValues), Math.max(...xValues)])
    .range([CursorSize, chartWidth]);

  const scaleY = scaleLinear()
    .domain([Math.min(...yValues), Math.max(...yValues)])
    .range([chartHeight, CursorSize]);

  const linePath = shape
    .line<ChartCoordinates>()
    .x((d: ChartCoordinates) => scaleX(d.x))
    .y((d: ChartCoordinates) => scaleY(d.y))
    .curve(curveNatural)(data);

return (
<Svg
  width={width}
  height={height}
  viewBox={`0 0 ${width} ${height}`}
  style={{ maxWidth: "100%" }}
  preserveAspectRatio="none"
>
  <>
    <Path
      d={`${linePath} L ${width} ${height} L ${0} ${height}`}
      fill={`url(#${gradientId})`}
      strokeLinecap="round"
    />
    <Path
      d={linePath}
      fill="none"
      strokeWidth="3"
      strokeLinecap="round"
    />
  </>
</Svg>)

Thanks

mbostock commented 1 year ago

You can: