Home > OS >  How do I keep all the legends in ggplot
How do I keep all the legends in ggplot

Time:11-19

How do I keep all the legends in plot? Below is an example of scatter plot. It prints only if x > 0.5. But I want to show all the legends.

enter image description here enter image description here

library(tidyverse)

for (iter in 1:5)
{
  # generate 5 random points
  tbl <- tibble(x = runif(5),
                y = runif(5),
                class = c("A", "B", "C", "D", "E"))

  # print if x > 0.5
  p <- ggplot(data = tbl %>% filter(x > 0.5),
              aes(x = x,
                  y = y,
                  color = class))  
    geom_point(size = 5)  
    scale_fill_manual(labels = c("A", "B", "C", "D", "E"),
                      values = c("Grey", "Red", "Green", "Blue", "Yellow"),
                      drop = FALSE)  
    theme_bw()  
    theme(aspect.ratio = 1)  
    xlim(0, 1)  
    ylim(0, 1)

  ggsave(p,
         filename = paste0(iter, ".png"))
  
}

CodePudding user response:

You can do it if:

  • you set the class variable to factor
  • use scale_colour_manual instead of scale_fill_manual. If you want to use the default colour from the ggplot palette you can use scale_colour_descrete, as in my code.
library(tidyverse)

set.seed(1) # for reproducibility

plots <- lapply(1:5, function(iter){
  
  # generate 5 random points
  tbl <- tibble(x = runif(5),
                y = runif(5),
                class = factor(c("A", "B", "C", "D", "E")))
  
  # print if x > 0.5
  p <- ggplot(data = tbl %>% filter(x > 0.5),
              aes(x = x,
                  y = y,
                  color = class))  
    geom_point(size = 5)  
    scale_colour_discrete(drop = FALSE)  
    theme_bw()  
    theme(aspect.ratio = 1)  
    xlim(0, 1)  
    ylim(0, 1)
  
  ggsave(p, filename = paste0(iter, ".png"))
  
  p
})

# visualize them all together
cowplot::plot_grid(plotlist = plots)

enter image description here

PS: I've used lapply instead of a for loop, usually it is more appreciated by R users when possible.

CodePudding user response:

Instead of filtering out the data you can change the values to NA:

library(tidyverse)

for (iter in 1:5)
{
  # generate 5 random points
  tbl <- tibble(x = runif(5),
                y = runif(5),
                class = c("A", "B", "C", "D", "E"))
  
  # print if x > 0.5
  p <- ggplot(data = tbl %>% mutate(y = if_else(x > 0.5, y, NA_real_)),
              aes(x = x,
                  y = y,
                  color = class))  
    geom_point(size = 5)  
    scale_fill_manual(labels = c("A", "B", "C", "D", "E"),
                      values = c("Grey", "Red", "Green", "Blue", "Yellow"),
                      drop = FALSE)  
    theme_bw()  
    theme(aspect.ratio = 1)  
    xlim(0, 1)  
    ylim(0, 1)

  ggsave(p,
         filename = paste0(iter, ".png"))
}
  • Related