Xi Yang
Xi Yang

Reputation: 13

couldn't add legend to ggplot

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!

Upvotes: 0

Views: 162

Answers (1)

StupidWolf
StupidWolf

Reputation: 46978

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

Upvotes: 2

Related Questions