Coloring axvspan from range of colors (Python)
Question: **Background**

I am trying to plot consecutive colored areas in **Python** using
**matplotlib**. I use (imagine i being some iteration variable)

    
    
    axvspan(from_x[i], to_x[i], color=my_color[i])
    

to plot this.

Now, I need a general way to say "plot from green to increasingly more red
given N areas to be plotted next to each other".

    
    
    i = 0: area is green,
    i = 1: area is green but with some red,
    etc.
    i = N: area is red.
    

You get the point.

**Question** Sure, if N was fixed I could just manually put in the rgb values,
but it is not. I have looked up ways to do this if plotting lines etc. but I
am not sure how to do this for axvspan(...) and specifically how to get the
green to red feature. Most examples I found was regarding color maps which I
am not sure I want to use here.

Your help is much appreciated.


Answer: You can use an `(r,g,b)` tuple for the color, so we can just increase the red
and decrease the green as we move through the loop.

Obviously, you can manipulate `N` and the `from_x` and `to_x` arrays to suit
your needs.

    
    
    import matplotlib.pyplot as plt
    import numpy as np
    
    fig,ax = plt.subplots(1)
    
    N = 20
    
    from_x = np.linspace(0,0.95,N)
    to_x = from_x + 0.05
    
    for i in range(N):
        ri = float(i)/float(N)
        gi = 1.-ri
        bi = 0.
    
        ax.axvspan(from_x[i], to_x[i], color=(ri,gi,bi))
    
    plt.show()
    

[![enter image description
here](http://i.stack.imgur.com/FN8oB.png)](http://i.stack.imgur.com/FN8oB.png)

