AMisra
AMisra

Reputation: 1889

add a shape legend to ggplot R

I have a ggplot and I want to add a legend to it, but it reflects only color and not the shape. I used scale_shape_manual, but it still does not work. Here is what I have

plot <- ggplot(data.frame(labels, yes.percent.avgs.gc, yes.percent.avgs.dp, yes.percent.avgs.gm)) +
  geom_point(aes(x=labels, y=yes.percent.avgs.gc, colour="GC"), shape=16, size=5) + # Plot individual points
  geom_point(aes(x=labels, y=yes.percent.avgs.dp, colour="DP"), shape=17, size=5) + # Plot individual points
  geom_point(aes(x=labels, y=yes.percent.avgs.gm, colour="GM"), shape=18, size=5) + # Plot individual points
  geom_smooth(data=data.frame(labels, pred.avgs), aes(x=labels, y=pred.avgs, colour="Prediction Scores"), fill=NA, method=lm, size=1) +
  xlab("Bin range") +
  ylab("Argument Score") +
  theme(legend.position = c(0.8, 0.2))+
  scale_shape_manual(name = "Legend",
                     labels = c("GC", "DP", "GM"),
                     values = c(16, 17, 18))

plot # show the plot

How can I get the legend to show both color and shape.

Upvotes: 1

Views: 8891

Answers (1)

Mirek Długosz
Mirek Długosz

Reputation: 4275

Apparently, the problem is that you are putting three geom_point layers on top of each other. This confuses ggplot which uses all shapes at once in legend.

The solution is to tidy your data before plotting it. Since you haven't provided reproducible example, I had to make it up.

library("ggplot2")
library("tidyr")
set.seed(123)
labels <- sample(c("L1","L2", "L3", "L4"), 12, replace = TRUE)
yes.percent.avgs.gc <- sample(1:100, 12)
yes.percent.avgs.dp <- sample(1:100, 12)
yes.percent.avgs.gm <- sample(1:100, 12)

tidy.df <- gather(data.frame(labels, 
                             yes.percent.avgs.gc, 
                             yes.percent.avgs.dp, 
                             yes.percent.avgs.gm),
                  group, value,
                  yes.percent.avgs.gc, yes.percent.avgs.dp, yes.percent.avgs.gm)

plot <- ggplot(tidy.df) + 
  geom_point(aes(x=labels, y=value, colour=group, shape=group), size=5) + 
  xlab("Bin range") +
  ylab("Argument Score") + 
  scale_shape_manual(name = "Legend",
                     labels = c("GC", "DP", "GM"),
                     values = c(16, 17, 18)) + 
  scale_colour_manual(name="Legend",
                      labels=c("GC", "DP", "GM"),
                      values=c("Red", "Green", "Blue"))
print(plot)

ggplot

I have dropped geom_smooth call, because I could not see any difference between plots with and without it.

Upvotes: 4

Related Questions