ggplot中的条形图和geom_line

时间:2015-05-12 09:34:05

标签: r ggplot2 bar-chart

我想在条形图上绘制一个geom_line,我的酒吧按年份填充。 我的代码是:

library(ggplot2)
library(plyr)
library(reshape)

DF <- data.frame(DECL.INDICATORS=c("Finland", "Finland", "Germany" ,"Germany","Italy","Italy"),
                 Year=c(2009,2010,2009,2010,2009,2010),
                 EXPVAL=c(2136410,1462620,371845300,402397520,357341970,357341970),
                 IMPVAL=c(-33668520,-37837140,-283300110,-306157870,-103628920,-105191850))


net <- ddply(DF, .(Year,DECL.INDICATORS), summarise, 
                net = sum(EXPVAL + IMPVAL))

DF.m <- melt(DF, id.vars = c("Year", "DECL.INDICATORS"))

ggplot(DF.m,aes(x=DECL.INDICATORS,y=value, fill=factor(Year)))+
  geom_bar(stat="identity",position="dodge",colour="darkgreen")

last_plot() + geom_line(data = net, aes(DECL.INDICATORS, net,group = 1), size = 1) + geom_hline(yintercept = 0,colour = "grey90")

我想解决的问题是为每个国家芬兰,德国,意大利绘制三条线(从net净出口)。

使用我的最后一个代码行,我只得到三个与行连接的点

1 个答案:

答案 0 :(得分:2)

你应该使用facet代替。这样很明显,您只是在一个国家内进行比较,而不是在国家之间进行比较。

ggplot(DF.m, aes(x = factor(Year), y = value, fill = factor(Year))) +
  geom_bar(stat = "identity", position = "dodge", colour="darkgreen") + 
  facet_grid(~DECL.INDICATORS) + 
  geom_line(data = net, aes(y = net, group = 1))