You can build a guide extension, which requires ggplot2 3.5.0+. First we need a constructor function that just passes a new parameter max
to the guide, which will serve as the level to which the 'mercury' in the thermometer rises.
library(ggplot2)
guide_thermometer <- function(max, ...) {
new_guide(
max = max,
..., # Other parameters that colourbars accept
super = GuideThermometer
)
}
Next we need a new guide class. Below, we're inheriting from the colourbar guide, registering the max
parameter and tweaking the build_decor()
method. The gist of the tweak is that we're re-using the colourbar guide's method of building the gradient and then using a rounded rectangle to clip the gradient (and also serve as a frame).
GuideThermometer <- ggproto(
"GuideThermometer", GuideColourbar,
# Registering the 'max' parameter as valid
params = c(GuideColourbar$params, list(max = NULL)),
build_decor = function(decor, grobs, elements, params) {
# Setting the 'mercury level'
if (!is.null(params$max)) {
decor$colour[decor$value > params$max] <- NA
}
# Re-use the coloubar method to build gradient
grobs <- GuideColourbar$build_decor(decor, grobs, elements, params)
# Make a rounded rectangle
rounded <- grid::roundrectGrob(
r = unit(0.5, "snpc"),
gp = grid::gpar(fill = NA)
)
# Replace the frame with rounded rectangle
grobs$frame <- rounded
# Use rounded rectangle as a clipping path
grobs$bar <- grid::editGrob(
grobs$bar,
vp = grid::viewport(clip = rounded)
)
grobs
}
)
Lastly, you can use the new guide like below. Adding the smiley is just a matter of setting the right breaks
and label
in the scale.
ggplot(mpg, aes(displ, hwy, colour = cty)) +
geom_point() +
scale_colour_viridis_c(
guide = guide_thermometer(max = 25),
breaks = 25, label = "\u263a"
) +
theme(legend.text = element_text(size = 16))
Created on 2024-04-12 with reprex v2.1.0
Disclaimer: I have no idea how this will pan out in shiny. Might need to use a device that supports the graphics features introduced in R 4.1.0, I think, due to the clipping path.
Hmisc
rdrr.io/cran/Hmisc/man/latexTherm.html – Corena