Tom Martens
Tom Martens

Reputation: 776

geom_point with different legend for fill and shape

Hmmm, maybe it's the temprature or I'm once again do not see the obvious ...

Here is my code:

library(ggplot2)

p <- ggplot()
p <- p + geom_point(aes(x = 1, y=1,bg = "I", group = "B"),pch = 21, size = 20, color=NA)
p <- p + geom_point(aes(x = 1, y=1.125,bg = "I", group = "B" ),pch = 22, size = 20, color=NA)
p <- p + geom_point(aes(x = 0.75, y=1.125,bg = "II", group = "A" ),pch = 22, size = 20, color=NA)
p <- p + geom_point(aes(x = 0.85, y=1.125,bg = "III", group = "A" ),pch = 22, size = 20, color=NA)
p <- p + scale_fill_manual(values= c("darkred", "darkblue", "darkgreen"), guide=guide_legend(override.aes = list(shape = 23)))
#p <- p + scale_fill_manual(values= c("darkred", "darkblue", "darkgreen"), guide=guide_legend(inherit.aes = FALSE))
p <- p + scale_shape_manual(labels = c("circle", "rectangle"),values = c(21, 22))
p

What I'm trying to achieve are basically two legends, one that reflects the color, in this example there are three different colors ("I", "II", and "III"), and two different types of shapes "rectangle" and "circle", there will never be more than these two different shapes.

Unfortunately there are some additional constraints ... I can't use the aesthetic color due to the fact that I'm also using geom_segment to somehow connect the shapes, and that is the second constraint, I have to use ggplot2.

But I'not able to produce these two legends, any help is appreciated ...

Upvotes: 3

Views: 4073

Answers (1)

tonytonov
tonytonov

Reputation: 25618

Why don't you store all your points in a data frame? It suits perfectly:

df <- data.frame(x = c(1, 1, 0.75, 0.85), 
                 y = c(1, 1.125, 1.125, 1.125), 
                 nr = c("I", "I", "II", "III"), 
                 sh = c("B", "B", "A", "A"))

And now you can easily see the required mapping:

ggplot(df, aes(x, y, fill = nr, shape = sh)) + 
  geom_point(size = 20, color = NA) + 
  scale_shape_manual(labels = c("circle", "rectangle"), values = c(21, 22), 
                     guide = guide_legend(override.aes = list(colour = 1))) + 
  scale_fill_manual(values = c("darkred", "darkblue", "darkgreen"), 
                    guide = guide_legend(override.aes = list(shape = 23)))

enter image description here

Upvotes: 6

Related Questions