I'm making a plot with a long legend label, and I'd like to resize the fill key so that it is square (i.e. does not extent to the top and bottom of the label text). I can use theme()
or guide_legend()
to make the legend key height as tall as I want, but I can't get it to be any smaller than the height of the wrapped text. Is there a way to override this minimum dimension?
Minimal code example included-- the first one successfully makes the key tall, but the second one fails to make the key short (which is what I want to happen).
theme_set(theme_bw())
df <- data.frame(x = rnorm(100))
ggplot(df)
geom_histogram(
aes(x = x, fill = 'this text is \nway too long to \nfit on one line'))
theme(legend.key.height = unit(50, 'mm'))
ggplot(df)
geom_histogram(
aes(x = x, fill = 'this text is \nway too long to \nfit on one line'))
theme(legend.key.height = unit(0.001, 'mm'))
CodePudding user response:
I'm not aware of a way to do this natively. I think your two options are either to go down the route of writing your own draw key, as in the link Stefan supplied, or try something a bit simpler but more of a hack, like this:
legend_height <- 8
ggplot(df)
geom_histogram(
aes(x = x, fill = 'this text is \nway too long to \nfit on one line'),
key_glyph = draw_key_path)
guides(fill = guide_legend(override.aes = list(
size = legend_height, colour = "#f8766d")))
Or, with legend_height <- 2
, you get: