简体   繁体   English

ggplot图例图条和线

[英]ggplot Legend Bar and Line in Same Graph

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. 我在同一张图表上绘制条形图和折线图,我想知道是否有办法让ggplot的图例说条形是一件事,而线是另一件事。 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))
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="")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM