ggplot图例图条和线在同一图中 [英] ggplot Legend Bar and Line in Same Graph

查看:317
本文介绍了ggplot图例图条和线在同一图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在同一张图表上绘制条形图和折线图,我想知道是否有办法让ggplot的图例说条形是针对一件事的,而折线是针对另一件事的.就是说,我没有知道他们要填写的内容,而是知道行=西红柿",酒吧=土豆".

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".

数据:

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

这篇关于ggplot图例图条和线在同一图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆