R 在ggplot2中的堆叠条形图顶部绘制线

R 在ggplot2中的堆叠条形图顶部绘制线,r,ggplot2,R,Ggplot2,我已经创建了一个堆叠条形图,现在我想在同一个图形上画一条线,但我想不出来。我已经在ggplot调用中添加了geom_line(),但最后只得到了一条线,而不是条形图 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 = stoc

我已经创建了一个堆叠条形图,现在我想在同一个图形上画一条线,但我想不出来。我已经在ggplot调用中添加了geom_line(),但最后只得到了一条线,而不是条形图

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))
库(ggplot2)
图书馆(重塑)
#首先,让我们为堆叠图/线图示例制作一个玩具数据集。
年份=c(1,2,3,4,5,6)
股票=c(2,4,3,2,4,3)
出口=库存*2
国内=股票*3
产量=c(15,16,15,16,15,16)
#制作2个df:alldata用于堆叠条形图,linedata用于在其上绘制一条线。
alldata=data.frame(年份、库存、出口、国内)
linedata=data.frame(年份、生产)
#使堆叠的所有数据为“长”
MELTEDATA=melt(所有数据,id.vars=“年”)
#这很好:(但是hooboy很难用w/stat=“identity”来确定订单)
图1您很接近:

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

plotS1供将来参考,请记住包含您的库语句。@Hack-R-Doh!修好了,不用担心。干杯