在ggplot2的堆积条形图顶部绘制线条 [英] Plot line on top of stacked bar chart in ggplot2

查看:113
本文介绍了在ggplot2的堆积条形图顶部绘制线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个堆叠条形图,现在我想在同一个图形上划一条线,但我无法弄清楚。我已经将geom_line()添加到ggplot调用中,但是我只能以行,而不是条形图结束。

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.

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


推荐答案

您已关闭:

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

这篇关于在ggplot2的堆积条形图顶部绘制线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆