Apply a uniform gradient to floating bar chart

Greetings, all.

In the Plot Gallery, I see there is a way to apply a gradient fill to elements in a bar chart. However, I noticed that the gradient basically “starts over” on each bar, instead of being attached to a fixed value. Is there a way to apply a single gradient to the entire chart where the color values are determined based on their values?

I’ve created a notebook that illustrates the situation. Any thoughts or suggestions would be appreciated. Absolute Gradients for Bar Charts / Charles Lattimer | Observable


1 Like

I think you should be able to do this by setting gradientUnits="userSpaceOnUse"

See, Step 2 here: Playfair's Wheat and Wages / Jo Wood | Observable

1 Like

And, if you want to position the gradient with the y scale, scales are passed as the second argument to the render function, so you can do:

  marks: [
    (index, { y }) => htl.svg`<defs>
      <linearGradient id="gradient" gradientUnits="userSpaceOnUse"
        x1=0 x2=0 y1=${y(100)} y2=${y(0)}>
        <stop offset="0%" stop-color="red" />
        <stop offset="50%" stop-color="white" />
        <stop offset="100%" stop-color="blue" />

note however that since the temperatures don’t go from 0 to 100 this will mostly be in the red region. But you can now adapt in “data space”, by having e.g. y2=${y(60)} if 60 is the lowest temperature.

1 Like

Brilliant–thanks, jwoLondon and Fil!

I’ve added the solution in the Plot gallery.

1 Like