Figured out that the legend wasn't being extracted because the legend.position
was set to "bottom"
.
To obtain the legend when legend.position = "bottom"
use cowplot::get_plot_component(legendplot,"guide-box-bottom")
rather than cowplot::get_legend(legendplot)
Change the value guide-box
to one of the following values to match the position supplied in theme(legend.position="")
if you aren't using the default legend.position
:
guide-box-right
when legend.position="right"
,guide-box-left
when legend.position="left"
,guide-box-bottom
when legend.position="bottom"
,guide-box-top
when legend.position="top"
,guide-box-inside
when legend.position="inside"
library(cowplot); library(patchwork); library(grid); library(tidyverse)
#Data to create legend
legend_data <- data.frame(
julian = 299:366,
PM25 = c(3.4,1.3,1.2,1.2,0.4,3.4,1.0,0.8,0.3,13.5,0.9,5.3,4.4,3.4,98.6,0.7,350.6,0.8,0.3,0.9,0.9,4.1,0.7,0.3,0.4,2.1,1.4,5.2,4.2,3.9,1.4,0.8,0.7,0.8,0.3,1.9,0.8,0.7,1.2,1.7,67.9,3.8,6.1,5.9,225.3,0.7,0.3,0.6,2.9,37.5,1.1,33.2,0.9,1.5,1.1,0.8,1.5,0.8,2.2,4.6,1.2,1.0,3.3,0.9,0.9,4.6,1.2,2.8),
site_name = "community 1"
)
legend_data$AQI <- case_when(
legend_data$PM25 <= 9.0 ~ "1",
legend_data$PM25 >= 9.1 & legend_data$PM25 <= 35.4 ~ "2",
legend_data$PM25 >= 35.5 & legend_data$PM25 <= 55.4 ~ "3",
legend_data$PM25 >= 55.5 & legend_data$PM25 <= 125.4 ~ "4",
legend_data$PM25 >= 125.5 & legend_data$PM25 <= 225.4 ~ "5",
legend_data$PM25 >= 225.5 ~ "6",
TRUE ~ NA_character_
)
#Create plot
legendplot <- ggplot(legend_data, aes(x=julian, y=AQI, fill=AQI)) +
geom_tile() +
scale_fill_manual(
values = c("green", "yellow", "orange", "red", "purple", "maroon"),
labels = c("1" = "Good", "2"="Moderate", "3" = "Unhealthy for\nSensitive Groups", "4" = "Unhealthy", "5" = "Very Unhealthy", "6" = "Hazardous")
) +
theme(legend.position = "bottom")
legendplot
#Extract legend
legend<-cowplot::get_plot_component(legendplot,"guide-box-bottom")
grid.newpage()
grid.draw(legend)