Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show letters as key glyphs for geom_text legend instead of default 'a'

Tags:

r

legend

ggplot2

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:

Desired result

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:

example without desired labels

This might be related to this issue: https://github.com/tidyverse/ggplot2/issues/2004, but perhaps there's a workaround?

like image 640
Tom Francart Avatar asked Jul 24 '18 13:07

Tom Francart


People also ask

How to change ggplot legend text?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

How do I add a legend in ggplot2?

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.

Do not show legend ggplot?

By specifying legend. position=”none” you're telling ggplot2 to remove all legends from the plot.


1 Answers

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))

enter image description here

like image 102
pogibas Avatar answered Oct 07 '22 23:10

pogibas