Home > front end >  How to create a custom legend with ggplot2 and ggarrange?
How to create a custom legend with ggplot2 and ggarrange?

Time:11-18

I am having issues creating a custom legend when using function plots

In other words, I have a set list of colours with custom text, and I want them all to be included in the legend, regardless of the colours used in the plot.

The colours I want for the legend are stored in object chart:

chart <- structure(list(plotvals = c(0.2, 0.4, 0.6, 0.8, 1), Colour = c( 
"#000080", "#87CEFA", "#00FF00", "#FFA500", "#FF0000")), row.names = c(1L, 
2L, 3L, 4L, 5L), class = "data.frame")

> chart
  plotvals  Colour
1      0.2 #000080
2      0.4 #87CEFA
3      0.6 #00FF00
4      0.8 #FFA500
5      1.0 #FF0000

I can create the plot on the left as follows:

df <- structure(list(pos = c(82304304L, 82402792L, 82567842L, 82646930L, 
82686681L), val = c(0.0336705048361217, 0.0304909014034332, 3.21204387671607, 
2.28366271211045, 1.7182850299727), Colour = c("#000080", "#000080", 
"#87CEFA", "#00FF00", "#87CEFA")), row.names = c(1L, 2L, 3L, 
4L, 5L), class = "data.frame")

> df
       pos       val  Colour
1 82304304 0.0336705 #000080
2 82402792 0.0304909 #000080
3 82567842 3.2120439 #87CEFA
4 82646930 2.2836627 #00FF00
5 82686681 1.7182850 #87CEFA


plot1 <- ggplot(df, aes(pos, rep(1, times = nrow(df))))   
      geom_point(shape = "\u007C", size = 5)   
      theme_void() 

plot2 <- ggplot(df, aes(pos, val, colour = Colour))  
      geom_point()   
      ylim(0, 4)  
      theme_bw()  
      scale_color_identity(guide = "legend")

plots <- ggarrange(plot1, plot2, heights = c(0.5, 6),
    ncol = 1, nrow = 2, align = "v", common.legend = TRUE, legend = "right")

png("plots.png")
plots
dev.off()

How do I adjust the legend so that it is custom, but still functions with ggarrange?

CodePudding user response:

Not sure whether this works for your real case but for the example data one option would be to set the limits and the labels of the color scale according to your chart df plus some additional hacks via guide_legend, i.e. use a rectangle shape and setting the size:

library(ggplot2)
library(ggpubr)

plot1 <- ggplot(df, aes(pos, rep(1, times = nrow(df))))  
  geom_point(shape = "\u007C", size = 5)  
  theme_void()

plot2 <- ggplot(df, aes(pos, val))  
  geom_point(aes(colour = Colour))  
  theme_bw()  
  scale_color_identity(
    guide = guide_legend(reverse = TRUE, override.aes = list(shape = 15, size = 5)),
    limits = chart$Colour, labels = scales::number(chart$plotvals)
  )  
  scale_fill_manual(values = chart$Colour)

plots <- ggarrange(plot1, plot2,
  heights = c(0.5, 6),
  ncol = 1, nrow = 2, align = "v", common.legend = TRUE, legend = "right"
)

enter image description here

  • Related