2

I'm plotting a bar graph and a line graph on the same chart, and I was wondering if there was a way to have the legend for ggplot say that the bar is for one thing, and the line is for another. That is, rather than identifying what they fill by, which is what I know how to do, have something that says "line = tomatoes", "bar = potatoes".

Data:

x <- c(0:10)
y1 <- c(0,.5,1,1.5,2,2.5,3,3.5,4,4.5,5)
y2 <- append(c(1:5),c(6,8,10,12,14,16))
mydata <- as.data.frame(cbind(x,y1,y2))
hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
riders994
  • 1,246
  • 5
  • 13
  • 33

1 Answers1

4
x=c(0:10)

See code below. You need to have aesthetic mappings for the legend to show. Anyone else looking at this feel free to suggest a way to do this on a single legend to get rid of the somewhat ugly looking space between the two.

y1=c(0,.5,1,1.5,2,2.5,3,3.5,4,4.5,5)
y2=append(c(1:5),c(6,8,10,12,14,16))
mydata1=data.frame(x=x,line=y2,Type="Line")
mydata2=data.frame(x=x,bar=y1,Type="Bar")

ggplot(data=mydata1) + geom_line(aes(x=x,y=line,linetype=Type)) +
  geom_bar(data=mydata2,aes(x=x,y=bar,fill=Type),stat="identity") +
  scale_fill_manual(values=c("black","black")) +
  guides(fill = guide_legend(override.aes=list(fill=c("black")))) +
  labs(fill="", linetype="")
jrdnmdhl
  • 1,935
  • 18
  • 26