Julia plots: How to fill graph background with different colors

I am trying make a plot with the background colors different for each section of the y-axis. For example:

using Plots
plot(Plots.fakedata(50, 1), w=3, fill = (0, 0.2, :red))

generates the image:

I want to fill the background of the graph with different colors. Like the area from -2 to 0 might be in red and be labelled as “risky”, from 0 to 2 as green and labelled as “ok”, etc.
Something like this:

plot(Plots.fakedata(50, 2), w=3)
hline!( [collect(-10:10)], color=[:red,:green], width=30, alpha=collect(0.1:0.1:0.2), legend=false)

which generates this:

I looked at the plots documentation and could not figure a way to do it. Does the fill keyword argument accept a list of fillrange, fillalpha and fillcolor? is there any other way to do it?

Do you mean something like this?

using Plots
data = Plots.fakedata(50,2)
p = plot(data, w=3);
hspan!(p,[0,maximum(data)], color = :green, alpha = 0.2, labels = "good");
hspan!(p,[minimum(data),0], color = :red, alpha = 0.2, labels = "bad");
display(p) # or savefig(p, "filename.png")


I’ve also tried combining the two calls to hspan!, but the backend didn’t like that on my pc - might work on yours.


Thanks @Sukera. This is exactly what I was trying to do!

That’s great! If my post solved your problem, please mark it as the solution so other people know that your question has been answered :slight_smile:

Is it possible to apply a gradient rather than a static color array to the background fill?

It’s straightforward to apply it to a curve/scatter plot, but I can’t get the background gradient to work (using Plots).

Check this past post for a beautiful solution by @klaff using Plots, Colors and PolygonOps.

Thanks! I’ll have to take some time to understand that code.

I think I found fill might actually work better for my application: reflectance spectrum as a function of wavelength in the visible range.



In reviewing this post, it appears that the following code more directly answers the OP’s question:

NB: Congratulazioni Italia!

using Plots; gr()

x = LinRange(0,π,2021);  y =  2*cos.(x)
ymin, ymax = extrema(y)
c = [-1.; 1.]  # BAD < -1 ;  -1 < OK < 1;   GOOD > 1
cs = @. (c - ymin)/(ymax - ymin)   # map input data ranges to color scale 0-1 range:
my_cgrad2 = cgrad([:red,:white,:green], cs, categorical=true)

scatter([-1 -1 -1],[0 0 0], mc=[:red :white :green],label=["BAD < -1" "-1 < OK < 1" "GOOD > 1"],marker=:rect, ratio=1)
plot!(x,y, fill=true,fill_z=y,fc=my_cgrad2, colorbar=false,clims=(ymin,ymax),lc=:black,
     xlabel="x", ylabel="y", widen=false,label=false, xlims=extrema(x),ylims=(-2.1,2.1))
plot!(xticks=([0, pi/3, 2pi/3, pi], ["0","π/3","2π/3", "π"]), dpi=300)