0

I'm trying to add legend to the ggplot, and here is what I've tried (the data is just 3 simple columns of numbers.).

ggplot(data, aes(x = instant, y = cnt))+
  geom_point(aes(instant, cnt), color = rgb(0.45,0.63,0.76, 0.7))+
  geom_point(aes(instant, registered), color = rgb(0.70,0.52,0.75, 0.5))+
  geom_point(aes(instant, casual), color = rgb(0.95,0.61,0.73, 0.5))+
  theme(legend.position="right")

data example like :

data <- data.frame(matrix(c(1,2,3,3,5,9,1,2,4,2,3,5),3,4))
colnames(data) <- c("instant", "cnt", "registered", "casual")

which cnt is sum of registered and casual, and instant is index number.

the 3 colors represents different variables, and I would like to label them in the legend. It doesn't work as I expected. I only know legend() would work in plot(), so how can I add legend in ggplot?

Thanks for any help!

Community
  • 1
  • 1
Xi Yang
  • 13
  • 2
  • 1
    Can you provide a reproducible example of your data ? check this link: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – dc37 Dec 07 '19 at 22:33
  • Does this thread answer your question? https://stackoverflow.com/questions/48768567/reasons-that-ggplot2-legend-does-not-appear – MBorg Dec 07 '19 at 23:13
  • edited! sorry about that – Xi Yang Dec 07 '19 at 23:13
  • Does this answer your question? [Reasons that ggplot2 legend does not appear](https://stackoverflow.com/questions/48768567/reasons-that-ggplot2-legend-does-not-appear) – camille Dec 08 '19 at 01:28

1 Answers1

2
data <- data.frame(matrix(c(1,2,3,3,5,9,1,2,4,2,3,5),3,4))
colnames(data) <- c("instant", "cnt", "registered", "casual")

you need to make it long format, but first we set the colors:

COLS = c(rgb(0.45,0.63,0.76, 0.7),rgb(0.70,0.52,0.75, 0.5),rgb(0.95,0.61,0.73, 0.5))
names(COLS) = c("cnt","registered","casual")

And then make it long using tidyr:

library(tidyr)

data %>% 
pivot_longer(-instant) %>% 
ggplot(aes(x=instant,y=value,col=name)) + 
geom_point() +
scale_color_manual(values=COLS)

enter image description here

StupidWolf
  • 45,075
  • 17
  • 40
  • 72