Home > front end >  How do I add a graphical legend to the bottom of a figure using ggplot?
How do I add a graphical legend to the bottom of a figure using ggplot?

Time:10-06

I am interested in creating a figure using ggplot2 similar to the one drafted enter image description here

CodePudding user response:

Here's a similar idea to Stefan's

plot <- ggplot(data1, aes(x=specification, y=point))  
  geom_errorbar(width=0.1, aes(ymin=lower, ymax=upper))  
  geom_point(shape=21, size=0.5, fill="black")  
  ylab("Effect")  
  xlab("")  
  theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=1))  
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
            alpha = 0.1, fill = "blue",
            data = transform(rect, variable = c("Var 1", "Var 2")),
            inherit.aes = FALSE)  
  theme_minimal(base_size = 16)  
  theme(axis.text.x = element_blank(), 
        strip.background = element_rect(fill = "gray85", color = NA))   
  facet_wrap(vars(variable), ncol = 1)

plot2 <- ggplot(data1, aes(x = 1, y = 2, fill = treatment_info))  
  geom_tile(color = "black", size = 0.5)  
  geom_text(aes(y = 1, label = treatment_size), check_overlap = TRUE, size = 5)  
  scale_y_continuous(limits = c(0.5, 2.5), expand = c(0, 0), name = "",
                     breaks = 1:2, labels = c("Size", "Count"))  
  facet_grid(~specification)  
  theme_minimal(base_size = 16)  
  scale_x_discrete(expand = c(0, 0), name = "")  
  scale_fill_manual(values = c("#d9ead3", "#e6b8af"))  
  theme(axis.text.y = element_text(),
        strip.background = element_rect(fill = "gray85", color = NA),
        legend.position = "none",
        panel.spacing = unit(0, "mm"),
        panel.background = element_rect(),
        panel.grid = element_blank(),) 

Now plot with patchwork

library(patchwork)

plot   plot2   plot_layout(ncol = 1, heights = 2:1)

enter image description here

  • Related