Home > Software engineering >  Add a color for each row in a corrplot with R
Add a color for each row in a corrplot with R

Time:10-19

I want to add a colour to each "row" of the corrplot but I haven't found any solution yet.

My code looks like this:

#install.packages("corrplot")
library("corrplot")

df <- matrix(runif(60, 20, 30), 8)

Labels <- c("var1", "var2", "var3", "var4", "var5", "var6", "var7", "var8")
LabelColRow <- c("red", "blue", "green", "yellow", "purple", "black", "grey")

rownames(df) <- Labels
colnames(df) <- Labels

corrplot(df, 
         is.corr = FALSE,        
         method = "circle",      
         mar = c(2, 1, 3, 1),
         addgrid.col = "NA",     
         cl.pos = "n",
         tl.cex = 0.75,         
         tl.col = "black",      
         tl.srt = 360,          
         tl.offset = 0.9,       
         tl.pos = "lt"
)

So basically I want the "row" of var1 to be red, the row for var2 blue, etc.

Edit: Here an example

CodePudding user response:

It doesn't look like corrplot offers the functionality to colour by row. The alternative would be to build the chart in ggplot. More work, for sure, but it allows the flexibility to colour rows.

As a start of a solution:

df %>% 
  as.data.frame() %>% 
  rowid_to_column() %>% 
  pivot_longer(-rowid) %>% 
  
  ggplot()  
  geom_point(aes(x = name, y = rowid, size = value, colour = factor(rowid)) )  
  geom_text(aes(x = name, y = rowid, label = round(value,0)))  
  scale_size(range = c(0, 20))  
  scale_colour_manual(values = c("blue", "green", "red", "orange", "grey", "purple", "darkblue", "black", "green"))  
  guides(colour = "none", size = "none")  
  labs(x = NULL, y = NULL)

enter image description here

  • Related