rggplot2

In ggplot2 how can I display in single legend the line color and point shape mapped to vector of single-character strings?


Haven't found any post that address this issue specifically.

In the following chart I'd like to use a column of single-character strings as the shapes for geom_point(). The help vignette ggplot2-specs says a single character string can be specified.

I want to see "4", "6", and "8" used as the point shapes (instead of circle, triangle, and square). But it doesn't seem to work. And if it did work, I'd like to see one legend (instead of two).

library(dplyr); library(ggplot2)

mtcars2 <- mtcars %>% 
  inner_join(data.frame(cyl=c(4,6,8), 
                        cyl_word=c('four','six','eight')))

p <- ggplot(mtcars2, aes(mpg, wt, color=cyl_word)) + geom_line()

p + geom_point(aes(shape=factor(cyl)), size=3)

geom_point

Using geom_text() instead of geom_point() yields something closer to the desired results. What is missing from them is that the shapes ("4", "6", "8") don't appear in the legend (I suspect the letter "a" in the legend is the indicator of geom_text() and that it is unchangeable ... is that right?)

p + geom_text(aes(label=factor(cyl)), size=6)

enter image description here

Don't know if maybe I should be using scale_shape_?()


Solution

  • We can map the shape to cyl_word and force manual shapes:

    ggplot(mtcars2, aes(mpg, wt, color=cyl_word)) +
      geom_line() +
      geom_point(aes(shape=cyl_word), size=3) +
      scale_shape_manual(values = setNames(as.character(mtcars2$cyl), mtcars2$cyl_word))
    

    mtcars plot with letters in the legend

    Clearly the order appears non-numeric, that can be address with factors.