Problem with RColorBrewer palette

I am struggling trying to generate a specific color palette to be used in a network for coloring edges. I have created a simple example:


w = runif(100, min=-1, max=1)

colors = RColorBrewer::brewer.pal(n=10, name="RdYlBu")[as.numeric(as.factor(w))]

I would like to classify all that continuous values between -1 and 1, generating a color palette of 10 different colors. However, lots of NAs are generated.

Why is this happening?

Thanks in advance for any help!

Hi, you have 10 colours, but 100 factor levels. Use cut() to bin the numbers and you're fine.

w = runif(100, min=-1, max=1)                                    
w_fac  <- cut(w, breaks = seq(-1, 1, length.out = 10))           
colors = RColorBrewer::brewer.pal(n=10, name="RdYlBu")[w_fac]    
# colors                                                         
# #4575B4 #74ADD1 #A50026 #ABD9E9 #D73027 #E0F3F8                
#      10      14      11       5       9      10                
# #F46D43 #FDAE61 #FEE090                                        
#      15      12      14                                        

Does this help?


1 Like

Yes! It is exactly what I was looking for

Thanks @Jwvz001 for your help!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.