在ggplot2中绘制另一个的顶部

时间:2013-01-30 18:53:50

标签: r plot ggplot2

如何在Y1的同一图中绘制引用Y2的线条和引用ggplot2的条形图?

这是我的数据:

   year       partbuild    mean.t       sd.t  n.t      se.tr       ci1       ci2
1  2003          Assets  6.072719  11.109798  173  0.8446623  4.417181  7.728257
2  2003 Non-opportunity  3.793043  59.377032 4394  0.8957534  2.037366  5.548720
3  2003     Opportunity  2.650684   7.397618  257  0.4614507  1.746240  3.555127
4  2004          Assets 11.334394  19.609274  173  1.4908655  8.412297 14.256490
5  2004 Non-opportunity  5.922468  38.776455 4394  0.5849760  4.775915  7.069021
6  2004     Opportunity  4.757593  21.598943  257  1.3473051  2.116875  7.398311
7  2005          Assets 13.580937  23.748005  368  1.2379504 11.154554 16.007319
8  2005 Non-opportunity  9.698966 154.769250 4009  2.4443683  4.908004 14.489928

这是我正在使用的代码

y.bar <- ddply(d1a, c('year', 'partbuild'), function(x) mean(x$transfers.cap, na.rm=T))
sd.tr <- ddply(d1a, c('year', 'partbuild'), function(x) sd(x$transfers.cap, na.rm=T)) 
n.tr <- ddply(d1a, c('year', 'partbuild'), function(x) length(x$transfers.cap))
db2 <- merge(y.bar, sd.tr, by=c('year', 'partbuild'))
db3 <- merge(db2, n.tr, by=c('year', 'partbuild'))
colnames(db3) <- c('year', 'partbuild', 'mean.t', 'sd.t', 'n.t')

p <- ggplot(db3, aes(y=mean.t, x=year, group=partbuild, shape=partbuild))
p + geom_point(aes(colour = partbuild), size=3.5) + geom_line(aes(colour = factor(partbuild)), size=1) + theme_bw() + ylab("Average of Federal Transfers per capita") + xlab("Year") + theme(axis.title.x = element_text(face='bold', size = 15, vjust = .25)) + theme(legend.title=element_blank()) + theme(axis.title.y = element_text(face="bold", size = 15, angle=90)) + scale_fill_discrete(name="") + theme(legend.text = element_text(colour="black", size = 13, face = "bold"))  + geom_vline(xintercept = c(2004, 2008), linetype="dashed" )

这是我得到的照片:

Sample plot

但是,我想在这些行后面绘制变量n.tr的区域。

我该怎么做?

2 个答案:

答案 0 :(得分:3)

Plot只显示部分数据,因为只提供了前8行。

首先,在函数ggplot()中提供x=colour=的值,因为这些值对于所有图层都是相同的。然后,为每个元素y=提供值。使用scale_y_log10(),因为n.tmean.t值之间存在很大差异。

p<-ggplot(data=db3,aes(x=year,colour=partbuild))
p+geom_bar(aes(y=n.t,fill=partbuild),stat="identity",position="dodge")+
 geom_line(aes(y=mean.t))+
  geom_point(aes(y=mean.t,shape=partbuild), size=3.5)+scale_y_log10()+theme_bw()

enter image description here

答案 1 :(得分:0)

GGplot默认使用这些颜色,但对于数据之上的数据,它并没有太大帮助。我想你可以试试:

p<-ggplot(data=db3,aes(x=year,colour=partbuild))
p+geom_bar(aes(y=n.t,fill=partbuild),stat="identity",position="dodge")+
 geom_line(aes(y=mean.t**, colour="black"**))+
  geom_point(aes(y=mean.t,shape=partbuild), size=3.5)+scale_y_log10()+theme_bw()

我希望这会有所帮助。