-1

I am trying to understand ggplot2 and I tried this code:

a=as.data.frame(c(2007:2016))
str(a)

b=runif(10, 1000, 2000) #vector
c=runif(10, 500,1000) #vector

ggplot(data=a, aes(x=a)) +
  geom_bar(aes(y=b), stat = "identity") +
  geom_line(aes(y=c), color="white", size=0.75)

that gave me this: enter image description here

Why is there no legend and how can I have one?

PilouPili
  • 2,601
  • 2
  • 17
  • 31
EGazzoli
  • 109
  • 3

1 Answers1

1

You need to specify your fills and colors, then a scale_color_manual and some theme setup.

ggplot(data=a, aes(x=a$`c(2007:2016)`)) +
  geom_bar(aes(y = b, fill = "b"), stat = "identity") +
  geom_line(aes(y = c, group = 1, color = "c"), size = 0.75) +
  scale_colour_manual(labels = "Line", values=c("c" = "white"))+
  scale_fill_manual(labels = "Bar",values="grey")+
  theme(legend.key=element_rect(fill = "grey"),
        legend.title=element_blank()) +
  labs(x = "Date", y = "Value")

enter image description here

Anonymous coward
  • 2,061
  • 1
  • 16
  • 29