ggplot Legend Bar and Line in Same Graph

谁都会走 提交于 2019-12-11 02:32:08

问题


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))

回答1:


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="")


来源:https://stackoverflow.com/questions/30464602/ggplot-legend-bar-and-line-in-same-graph

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!