How to create a patch/shape with a color gradient in a simple 2d plot?

Hi, I am trying to add a rectangle with a color gradient to a plot to indicate a special region that should fade out, i.e. have a color gradient to white. So far I have tried hpatch() and vpatch(), which give me the rectangle, but only in a solid color. I’ve managed to engineer a color gradient using a heatmap, but this overlays the xticks and yticks and is therefore not a suitable solution. I’ve tried to use fill, and then set the fill_z accordingly, but this gives me slices that do not interpolate nicely no matter how fine I make the spacing… here is some code to demonstrate what I try to achieve.

myCG = cgrad([:gray, :white]);
gridSpacing = 50;
xPatch = (1, 10);
yPatch = (0, +1);
x = range(xPatch[1], stop = xPatch[2], length = gridSpacing);
y = yPatch[2] * ones(length(x));
z = range(0, stop = 1, length = gridSpacing);
myPlot = plot(x, y, linecolor = :transparent, fillrange = yPatch[1], fillcolor = myCG, fill_z = z, legend = false)

Is there any simple way to do this?

Have you checked this post with a beautiful solution by @klaff using Plots, Colors and PolygonOps?

NB: please post your code above inside triple backticks

1 Like

Thanks for the suggestion. I came across this post already, but I felt like there has to be a simpler solution. Anyway, I will take a closer look at it again.

You may not want to switch plotting libraries for this, but in Makie you can use poly or mesh with a color for each point:

using GLMakie

    Point2f0[(0, 0), (0, 1), (1, 1), (1, 0)], 
    color = [:gray, :gray, :white, :white])

# Or with transparency to fade out even more:w
    Point2f0[(0, 0), (0, 1), (1, 1), (1, 0)], 
    color = [:gray, :gray, (:white, 0.0), (:white, 0.0)])


Thanks., this is exactly what I am looking for. I still didn’t manage to do this with GR, but maybe I can combine your suggestion with the rest of the plot.