Hi!! I am a Data Scientist at Children’s Hospital ...
# show-and-tell
s
Hi!! I am a Data Scientist at Children’s Hospital of Philadelphia. We recently started using Observable plots inside Quarto Notebooks for some reporting purposes. This may be real simple but I am novice with Observable, D3 and all. For this example https://observablehq.com/@observablehq/plot-walmart-density How would I prevent the density layer to stop overflowing from the nation line? Any help with code or reference to some other notebooks might be a huge help!
m
Requires a bit of D3 & SVG, but you can do it with a render transform and the SVG clip-path attribute.
Copy code
Plot.plot({
  projection: "albers",
  color: {scheme: "YlGnBu"},
  marks: [
    Plot.density(walmarts, {
      x: "longitude",
      y: "latitude",
      bandwidth: 10,
      fill: "density",
      render(index, scales, values, dimensions, context, next) {
        const {document} = context;
        const g = next(index, scales, values, dimensions, context);
        const clipPath = document.createElementNS("<http://www.w3.org/2000/svg>", "clipPath");
        const path = document.createElementNS("<http://www.w3.org/2000/svg>", "path");
        const geoPath = d3.geoPath(context.projection);
        path.setAttribute("d", geoPath(nation));
        clipPath.setAttribute("id", "clip");
        clipPath.appendChild(path);
        context.ownerSVGElement.appendChild(clipPath);
        g.setAttribute("clip-path", "url(#clip)");
        return g;
      }
    }),
    Plot.geo(statemesh, {strokeOpacity: 0.3}),
    Plot.geo(nation),
    Plot.dot(walmarts, {x: "longitude", y: "latitude", r: 1, fill: "currentColor"})
  ]
})
👀 1
👏 1
s
I finally got to use this code on my data and it worked like a charm!! Thanks so much @Mike Bostock. Huge fan of your work!!!🫡