I am trying to create a ggplot scatter plot with continuous fill and discrete color. I would like to place the colorbar at the bottom and the color legend inside the panel (see image below).
ggplot(mpg, aes(x = displ, y = cty, color = manufacturer, fill = year))+
geom_point(shape = 21) +
theme_classic() +
theme(legend.position = "bottom")
I found a solution with ggplot2::annotation_custom in combination with cowplot::as_grob and ggpubr::get_legend
# plot without the colorbar
p_nocolorbar<-
ggplot(mpg, aes(x = displ, y = cty, color = manufacturer, fill = year))+
geom_point(shape = 21) +
theme_classic() +
guides(fill = "none") +
theme(legend.position = "bottom")
# plot without the color legend
p_nolegend<-
ggplot(mpg, aes(x = displ, y = cty, color = manufacturer, fill = year))+
geom_point(shape = 21) +
theme_classic() +
guides(color = "none") +
theme(legend.position = "bottom")
# final plot
p_nolegend +
annotation_custom(grob = cowplot::as_grob(ggpubr::get_legend(p_nocolorbar)),
xmin = 4, xmax = 7,
ymin = 25, ymax = 30)
However, this method gets a bit tidious with more complex plots and I find possitioning and scaling of the legend difficult. Wondering if anyone has a better solution.