2016-10-15 113 views
1

我已經創建了一個堆疊的條形圖,現在我想在同一圖形上繪製一條線,但我無法弄清楚。我已經將geom_line()添加到了ggplot調用中,但是我只能結束而不是條形圖。在ggplot2中堆積的條形圖之上繪製線

library(ggplot2) 
library(reshape) 
# First let's make a toy dataset for our stacked plot/line plot example. 
year = c(1,2,3,4,5,6) 
stocks = c(2,4,3,2,4,3) 
exports = stocks*2 
domestic = stocks*3 
production = c(15,16,15,16,15,16) 

# Make 2 df's: alldata is for stacked bar chart, linedata is for plotting a line on top of it. 
alldata = data.frame(year,stocks,exports,domestic) 
linedata = data.frame(year,production) 

# Make alldata 'long' for the stacking 
melteddata = melt(alldata,id.vars="year") 

# This works fine: (but hooboy was tricky to figure out the ordering w/ stat="identity") 
plotS1 <- ggplot(melteddata, aes(x=year,y=value,factor=variable,fill=variable,order=-as.numeric(variable))) 
plotS1 + geom_bar(stat="identity") 

# This plots only the line, not the stacked bar chart : 
plotS1 <- ggplot(melteddata) 
plotS1 + geom_bar(aes(x=year,y=value,factor=variable,fill=variable,order=-as.numeric(variable)), stat="identity") 
plotS1 + geom_line(data=linedata, aes(x=year,y=production)) 
+0

以供將來參考,請記住,包括您的圖書館的聲明。 –

+0

@ Hack-R Doh!修復。 – YourEconProf

+0

不用擔心。乾杯。 –

回答

2

你接近:

plotS1 <- ggplot(melteddata) 
plotS1 + geom_bar(aes(x=year,y=value,factor=variable,fill=variable, 
         order=-as.numeric(variable)), stat="identity") + 
      geom_line(data=linedata, aes(x=year,y=production)) 

enter image description here