cibr
cibr

Reputation: 473

Making legend reflect geom_point type

I need to have a plot (with several y-variables) that is nice when seen in colour, but also can be understood when printed in black and white (greyscale). So I try geom_point shapes. Problem: I am not able to have the legend in ggplot2 reflect the shape of points in the plot.

Here are toy data:

# Defining vectors
gr <- c("group1", "group2", "group3")
v1 <- c(1.7, 1.5, 1.3)
v2 <- c(2.5, 2.1, 1.9)
v3 <- c(1.5, 1.8, 1.7)

# Combining vectors into one data frame
df <- data.frame(gr, v1, v2, v3)

Using the following code to develop a plot...

ggplot(df, aes(x=gr, group=1)) +
  # color ask for coloring, pch asks for point type
  geom_point(aes(y=v1, color="v1"), pch=19) + 
  geom_point(aes(y=v2, color="v2"), pch=0) + 
  geom_point(aes(y=v3, color="v3"), pch=24) + 
  geom_line(aes(y=v1, color="v1")) +
  geom_line(aes(y=v2, color="v2")) +
  geom_line(aes(y=v3, color="v3")) +
  theme_bw() 

... gives this result:

enter image description here

How do I make the point shapes in the legend reflect the point shapes used in the plot?

Upvotes: 0

Views: 186

Answers (1)

zx8754
zx8754

Reputation: 56259

Convert from wide-to-long then plot with group:

library(tidyr)
library(ggplot2)

# wide-to-long
plotDat <- gather(df, key = "version", value = "value", -gr)

# plot with group
ggplot(plotDat, aes(gr, value, col = version, shape = version, group = version)) +
  geom_point() +
  geom_line()

enter image description here

Upvotes: 2

Related Questions