Constructing arbitrary legends in `{ggplot2}` not directly related to a mapped aesthetic

Hello,

I am the lead developer of the {openairmaps} package, a package that (currently) creates dynamic air quality maps through extending the {openair} package. It effectively uses static polar plots as markers on an interactive map, and uses leaflet::addLegend() to draw a shared legend for all of them. {leaflet} allows you to draw any arbitrary legend just by providing a numeric scale and a colour palette to use - it is on you to make it match your data.

I'm questioning having static outputs also, which would be more useful for traditional reports. Adding a figure to a ggplot is easy enough with, e.g., {ggpath}, and I can add a basemap with {ggmap}, but I'm a bit lost on the shared legend.

Is it possible to create a "dummy" colorbar legend that isn't associated with any aesthetic in the ggplot2 object itself?

A very simple example - what could I add to ggplot(mtcars, aes(cyl, mpg) + geom_point() to draw a colour bar that goes from zero to one-hundred, totally unrelated to mtcars, cyl and mpg?

An ugly hack:

library(ggplot2)

ggplot(mtcars,aes(cyl, mpg,color=NA_real_)) + 
  geom_point() +
  scale_color_gradient(low="red",high="blue",
                       limits=c(0,100), name = "Test",na.value = "black")

Created on 2022-12-17 with reprex v2.0.2

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

Good enough for me! Cheers!