rggplot2plotggraph

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


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()

Solution

  • 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