I'm using geom_raster and geom_text to put a letter on each of the coloured rectangles in my plot. I'd like this letter to appear on top of the color boxes in the legend as well, but cannot figure out how.
I've tried adding show.legend=TRUE
to the geom_text
, but this results in the letter 'a' in each legend key, instead of the desired character.
The desired result looks as follows:
Here is code to reproduce the basic plot:
library(tidyverse)
d <-tribble(
~a, ~b, ~c,
"a", "l", "A",
"a", "r", "F",
"b", "l", "Q",
"b", "r", "R"
)
ggplot(data=d, aes(x=a, y=b, fill=c)) +
geom_raster(na.rm=TRUE) +
geom_text(aes(label=c), size=3, na.rm=TRUE)
And the output:
This might be related to this issue: https://github.com/tidyverse/ggplot2/issues/2004, but perhaps there's a workaround?
You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))
You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.
By specifying legend. position=”none” you're telling ggplot2 to remove all legends from the plot.
You can use geom_point
instead and specify point shape as letters with scale_shape_manual(values = d$c)
.
# We have to remove legend text and label with theme
ggplot(d, aes(a, b, fill = c, shape = c)) +
geom_raster() +
geom_point(size = 3) +
scale_shape_manual(values = d$c) +
theme(legend.text = element_text(size = 0),
legend.title = element_text(size = 0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With