简体   繁体   English

在ggplot2中的堆积条形图上绘制线条

[英]Plot line on top of stacked bar chart in ggplot2

I have created a stacked bar chart, and I would now like to plot a line on the same graphic, but I can't figure it out. 我创建了一个堆积条形图,我现在想在同一个图形上绘制一条线,但我无法弄明白。 I've added the geom_line() to the ggplot call, but I only end up with the line, not the bar chart. 我已经将geom_line()添加到ggplot调用中,但我最终只得到了行,而不是条形图。

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

You were close: 你很亲密:

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

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM