Home > Enterprise >  How to add a title and modify the color palette in a ggraph plot in R
How to add a title and modify the color palette in a ggraph plot in R

Time:11-05

I am working with packages see and ggraph in R to plot a correlation graph but I can't add the title of the plot and I can't change the colour palette. The MWE provided is as follows:

library(tidyverse) # for `%>%` and probably others
library(see) # for plotting
library(ggraph) # needs to be loaded
library(correlation) # obviously for `correlation`, which I noticed was installed as a dependency of pkg:see but apparently not loaded with it.

mtcars %>% 
correlation(partial = TRUE) %>% 
plot()

CodePudding user response:

Hopefully this will get you close to what you want, Jose:

cor_matrix <- cor(mtcars, method='pearson',use='complete.obs')
ggcorrplot(cor_matrix, method = c("square"), type = c("full"), 
           ggtheme = ggplot2::theme_minimal, 
           title = "Practice Title", show.legend = TRUE, 
           legend.title = "Corr", 
           show.diag = FALSE, outline.color = "gray", hc.order = TRUE, 
           lab = TRUE, 
           lab_col = "black", 
           lab_size = 2, tl.cex = 10, tl.col = "black", tl.srt = 45, digits = 2)   
  theme(
   legend.key.width = unit(.6, "cm"),   #to resize legend
   legend.key.height = unit(1.4, "cm"),
  )

CodePudding user response:

To change the edge color scale, you need to use one of the scale_edge_color* functions from ggraph:

library(correlation)
library(ggraph)
library(ggplot2)

p <- plot(correlation(mtcars, partial = TRUE))  
  scale_edge_color_gradientn(colours = c("red3", "gray90", "green4"))  
  ggtitle("Partial correlation of mtcars dataset")  
  coord_equal(clip = "off")

p

enter image description here

There seem to be limited options to change the fixed aesthetic parameters from within the plotting function, but you can change the layers the the produced ggplot object. You can also change theme elements as usual in a ggplot:

p$layers[[2]]$aes_params$colour <- "navy"
p$layers[[3]]$aes_params$size <- 6

p   theme(plot.background = element_rect(fill = "skyblue"),
          plot.title = element_text(hjust = 0.5))

enter image description here

  • Related