Ad

Python: Interpolate Between More Than 2 Colors

- 1 answer

In R, the colorRampPalette() function is very handy to interpolate between n colors in order to create new color palettes. I'm wondering whether there is a similar function somewhere in the Python packages ? Best

# The R code that I would like to translate
pal = colorRampPalette(c("blue", "yellow", "red"))(10)
plot(1:10, 1:10, col=pal, cex=10, pch=16)
Ad

Answer

Well, I am not aware of any direct methode to achive exactly the same result, however since there is no other response let me maybe point out how it is usually done with python if you come from r.

One way to choose a colour range is by picking a pre-made colour map of the matplotlib package. You can view most available colour maps here: https://matplotlib.org/users/colormaps.html.

Another nice function that creates a spectrum of colours depending on how many colours you want is the rainbow function which is used like this:

import matplotlib.cm as cm
NrCol = #Enter formula or methode to calculate total number of colours needed 
colour = cm.rainbow(np.linspace(0,1,NrCol))
for j in range(NrCol):
     color = colour[j] #this is the specific colour that you would never stand alone like this but rather use in a plot function

Of all the colours you get there, you could pick a certain range of course, but this would be a very rough, hard-coded solution.

Ad
source: stackoverflow.com
Ad