Bar graph and geom_line in ggplot

ぐ巨炮叔叔 提交于 2021-01-28 12:24:38

问题


I am trying to draw a geom_line on a bar chart, my bars are filled by year. My code is:

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

Problem I am trying to resolve is to draw a three lines (net export from net) for each country Finland, Germany, Italy.

With my last code line i am getting only three point which are connected with lines


回答1:


You should use facets instead. That way it is clear that you are only comparing within one country and not between countries.

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


来源:https://stackoverflow.com/questions/30186936/bar-graph-and-geom-line-in-ggplot

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