Question

i want to plot a chart in R using ggplot2, but with a manually defined legend. For each dataset, i want to plot both lines and points, with the same color. For different dataset, both the color and the shape of the point must be different, and i want this to be reflected in the legend. What I have at the moment is the following (the data is random, but in the same format as mine):

require(ggplot2)
x=runif(10,1,10)

y=runif(10,1,10)
df100final <- data.frame(x,y)
x=runif(10,1,10)
y=runif(10,1,10)
df80final <- data.frame(x,y)
x=runif(10,1,10)
y=runif(10,1,10)
df60final <- data.frame(x,y)

ggplot() +
  theme_bw() +
  stat_smooth(data=df100final, aes(x=x, y=y), se=FALSE) +
  geom_point(data=df100final, aes(x=x, y=y), shape=1) +
  stat_smooth(data=df80final, aes(x=x, y=y), se=FALSE) +
  geom_point(data=df80final, aes(x=x, y=y), shape=2) +
  stat_smooth(data=df60final, aes(x=x, y=y), se=FALSE) +
  geom_point(data=df60final, aes(x=x, y=y), shape=3) +
  scale_colour_manual(values=c("red","blue","green")) +
  theme(legend.position="top")

dev.off()

plot

As you can see, all the lines have the same color, as well as the points. Only the shape is different, and the legend is hidden.

* EDIT * If I put:

stat_smooth(data=df100final, aes(x=x, y=y, color="red"), se=FALSE) +
geom_point(data=df100final, aes(x=x, y=y, color="red"), shape=1) +
stat_smooth(data=df80final, aes(x=x, y=y, color="blue"), se=FALSE) +
geom_point(data=df80final, aes(x=x, y=y, color="blue"), shape=2) +
stat_smooth(data=df60final, aes(x=x, y=y, color="green"), se=FALSE) +
geom_point(data=df60final, aes(x=x, y=y, color="green"), shape=3) +

then i get this: enter image description here

but then i don't know how to edit the labels, and the symbols in the legend are all the same.

Was it helpful?

Solution

A more ggplot-esque way would be to collect your data in one data frame, create a grouping variable, and map colour to the grouping variable:

df <- rbind(df100final, df80final, df60final)
df$grp <- as.factor(rep(c(100, 80, 60), c(nrow(df100final), nrow(df80final), nrow(df60final))))

ggplot(data = df, aes(x = x, y = y, colour = grp, shape = grp)) +
  stat_smooth(se = FALSE) +
  geom_point() +
  scale_colour_manual(values=c("red", "blue", "green")) +
  theme_bw()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top