Answer to: Large heat map with multiple legends in ggplot
Score: 4
Instead of using patchwork an alternative approach would be to use the ggnewscale package to create your desired result as one chart, where ggnewscale allows you to map multiple variables onto the same aesthetic and include a legend for each.
First, I create two named lists: one for the variables to be mapped onto fill, and one for the fill scales. Secondly, I loop over the first list using purrr::imap to add a geom_tile and the respective fill scale for each variable.
library(tidyverse)
library(palmerpenguins)
var_fill <- list(
"Species" = "species",
"Sex" = "sex",
"Bill length" = "MEAN_BILL_LENGTH",
"Flipper length" = "MEAN_FLIPPER_LENGTH"
)
scale_fill <- list(
scale_fill_hue(guide = guide_legend(order = 1)),
scale_fill_manual(
values = c("white", "black"),
guide = guide_legend(order = 2)
),
scale_fill_fermenter(
type = "seq", palette = 2, direction = 1,
guide = guide_bins(order = 3)
),
scale_fill_fermenter(
type = "seq", palette = 3, direction = 1,
guide = guide_bins(order = 4)
)
)
names(scale_fill) <- names(var_fill)
var_levels <- names(var_fill)
ggplot(penguins_formatted, aes(y = uniqueID)) +
purrr::imap(
var_fill, \(x, y) {
list(
geom_tile(
aes(
x = y,
fill = .data[[x]]
),
color = "black",
width = .95
),
scale_fill[[y]],
ggnewscale::new_scale_fill()
)
}
) +
scale_x_discrete(
limits = var_levels
) +
coord_fixed(ratio = 1) +
theme_void() +
theme(
axis.text.y = element_blank(),
axis.text.x = element_text(
angle = 90,
hjust = 1
),
axis.title = element_blank(),
legend.position = "left",
panel.border = element_rect(fill = NA, linewidth = 0.8),
panel.background = element_rect(colour = NA, fill = "transparent"),
plot.background = element_rect(colour = NA, fill = "transparent"),
plot.margin = margin(0, 0, 0, 0, "cm"),
panel.spacing = unit(0, "cm"),
legend.title = element_blank()
)
View Question ↗
Question
Parent Entity
Score: 2 • Views: 44
Site: stackoverflow
SaaS Metrics