# Create sample data
set.seed(5642)
sample_data <- data.frame(
name = c("Geek1","Geek2","Geek3",
"Geek4","Geeek5") ,
value=c(31,12,15,28,45))
# Load ggplot2 and gridExtra
library("ggplot2")
library("gridExtra")
# Create both plot and store in variable without legend
plot1<-ggplot(sample_data,
aes(x = name, y = value, col=name)) +
geom_point(size=4)+
theme(legend.position = "none")
plot2<-ggplot(sample_data,
aes(x = name, y = value, fill=name)) +
geom_col()+
theme(legend.position = "none")
# combine both plots using grid.arrange()
combined_plot <- grid.arrange(plot1, plot2, ncol = 2)
# plot1 with legend
plot1_legend <- ggplot(sample_data,
aes(x = name, y = value, col=name)) +
geom_point(size=4)+
theme(legend.position = "bottom")
# function to extract legend from plot
get_only_legend <- function(plot) {
plot_table <- ggplot_gtable(ggplot_build(plot))
legend_plot <- which(sapply(plot_table$grobs, function(x) x$name) == "guide-box")
legend <- plot_table$grobs[[legend_plot]]
return(legend)
}
# extract legend from plot1 using above function
legend <- get_only_legend(plot1_legend)
# final combined plot with shared legend
grid.arrange(combined_plot, legend, nrow = 2, heights = c(10, 1))