Adding custom color scales to plots

I have a line plot simply constructed from a vector x and a vector y, I have then computed a colors vector which corresponds to each x value. I want to add a color scale of sorts below my plot (or on the plot but below the line) where the color aligns with the x values.

I came up with the solution to use a scatter plot

plot(x, y)
scatter!(x, fill(-0.5, length(x)), color=colors, label=false, marker=:rect, markersize=10)

On first inspection, this achieves what I want, but since the marker have significant width, the borders are off center and don’t align with the actual change in color. I tried to change the marker width but couldn’t figure out how.

What is the best way to do this?

Edit: I found a solution I was happy with but would be interested to see if there is a nicer way to do this!

1 Like

A solution I found acceptable is to use Shape to draw rectangles. Instead of using scatter(...), I used:

for i in eachindex(x)
    shape = Shape([x[i]-rw, x[i]-rw, x[i]-rw, x[i]-rw], 
                  [0, -1, -1, 0]) 
    plot!(shape, color=colors[i], linecolor=:transparent, label=false)

where rw is half the rectangle width, I actually found setting rw to be the full distance between x points to be best as when they perfectly aligned, I got a strange lines artifact. Of course, the y values of the rectangle should be adjusted, it worked for my purposes to but the rectangles between -1 and 0 vertically.