0
votes

I have a plot with several single geom_point-plots and I would like to specify the shape and color for each plot individually.

Somehow I am really struggling with getting a proper legend and also I could not find a solution on stackoverflow. I tried to use "fill" in the aes-command, but if I have more than two plots with fill, I get the error:

"Error: Aesthetics must be either length 1 or the same as the data (1): x, y"

This is a simplified minimal example of the basic structure of my plot:

da <- as.character(c(1:10))
type <- c("a", "b", "c", "a", "b", "c", "a", "b", "c", "a" )
value <- c(1:10)
df <- data.frame(da, type, value)

require("ggplot2")
ggplot() + 
  geom_point(data = subset(df, type %in% c("a")), aes(x=da, y=value), shape=1, color="red",  size=5) +
  geom_point(data = subset(df, type %in% c("b")), aes(x=da, y=value), shape=2, color="darkorange", size=3) +
  geom_point(data = subset(df, type %in% c("c")), aes(x=da, y=value), shape=3, color="violet", size=3) 

How can I add a legend with custom labels?

Thanks! :-)

1

1 Answers

2
votes

Why would you create separate layers and manually create a legend when you can simply create one layer and map aesthetics to your data (in this case, simply "type")? If you want specific colour or shape values, you can specify these using scales such as scale_colour_manual, scale_shape_discrete, etc)

da <- as.character(c(1:10))
type <- c("a", "b", "c", "a", "b", "c", "a", "b", "c", "a" )
value <- c(1:10)
df <- data.frame(da, type, value)

require("ggplot2")
#> Loading required package: ggplot2
ggplot(df, aes(x=da, y=value, color=type, shape = type, size = type)) + 
  geom_point()
#> Warning: Using size for a discrete variable is not advised.

Created on 2020-01-20 by the reprex package (v0.3.0)