Reasoning: I would like to easily use readily available continuous scales (from any package that offers scale_..._continuous etc), for ordinal factor-like data, e.g. mtcars$cyl. Because those data do only contain few sort of discrete values, I'd like to label the legend keys directly, and not the bin limits. How to do that?
library(ggplot2)
ggplot(mtcars, aes(mpg, disp, color = cyl))+
geom_point() +
scale_color_continuous(limits = range(mtcars$cyl),
guide = guide_colorsteps(ticks.colour = "black"))
Not desired:

Hacky way, which actually are four (!) hacks, and is not desired.
# Hack 1 - create the colors manually from the palette. This is already annoying.
cont_col <- colorRampPalette(c("#132B43","#56B1F7"))(length(unique(mtcars$cyl)))
# Hack 2- you need to modify the underlying draw_key function
# from https://github.com/tidyverse/ggplot2/issues/2844
draw_key_polygon2 <- function(data, params, size) {
lwd <- min(data$size, min(size) / 4)
grid::rectGrob(
width = grid::unit(1, "npc"),
height = grid::unit(1, "npc"),
gp = grid::gpar(
col = data$colour,
fill = alpha(data$fill, data$alpha),
lty = data$linetype,
lwd = lwd * .pt,
linejoin = "mitre"
))
}
# Hack 3 discretise the variable
ggplot(mtcars, aes(mpg, disp, color = as.character(cyl))) +
geom_point(key_glyph = "polygon2") +
scale_color_manual(values = cont_col) +
# Hack 4 override aes to change the fill of the key glyph polygons
guides(color = guide_legend(override.aes = list(fill = cont_col)))
But it results in the desired output

Created on 2021-05-02 by the reprex package (v2.0.0)


