Python "set_over" / "set_under" equivalent in R?

358 views Asked by At

If you want to have the upper and lower "caps"(outliers) of an interval to be displayed as distinct colors beyond the range of a colormap, you can use the set_over and set_under options in Python. I couldn't find any: Is there an equivalent in R?

This is what the colorbar should look like:

This is what the colorbar should look like

To produce this, I used the following code in Python:

clevels = np.arange(-18.0,6.0,1)
cs = plt.contourf(x,y,data[0,:,:],clevels, cmap=shifted_cmap) 

#take care of values beyond range of colormap
cs.cmap.set_under('darkblue') # exerything below range of colormap
cs.cmap.set_over('darkred')  # everything above range of colormap

# set range for colorbar (should be same as range for contour levels!)
cs.set_clim(-18.0, 5)

shifted_cmap is a colormap I produced using the following code:

def shiftedColorMap(cmap=plt.get_cmap('RdBu'), start=0, midpoint=0.75, stop=1.0, name='shiftedcmap'):
    # regular index to compute the colors
    reg_index = np.linspace(start, stop, 257)

    # shifted index to match the data
    shift_index = np.hstack([
    np.linspace(0.0, midpoint, 128, endpoint=False), 
    np.linspace(midpoint, 1.0, 129, endpoint=True)
    ])

    for ri, si in zip(reg_index, shift_index):
    r, g, b, a = cmap(ri)

    cdict['red'].append((si, r, r))
    cdict['green'].append((si, g, g))
    cdict['blue'].append((si, b, b))
    cdict['alpha'].append((si, a, a))

    newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict)
    plt.register_cmap(cmap=newcmap)

    return newcmap
0

There are 0 answers