0

I am trying to make a stacked line plot in ggplot2 with positive values stacked above the x-axis and negative values stacked separately below the x-axis. I have had success stacking each of the line types separately, but have not been able to have both on a single plot. I'm looking for some help on how I can do this, either by overlaying plots or doing something creative on a single plot.

My code below uses a simple ggplot with stacked geom_line plot. Half of the "Types" are positive values with respect to time and the other half of the "Types" are all negative values.

    p <- ggplot(dataForm, aes(x=Time,y=Value,group=Type),colour=factor(Type))
    p + geom_line(aes(fill = Type),position = "stack")

I have tried an alternative of specifying the positive and negative values separately without success:

    p <- ggplot(dataForm, aes(x=Time,y=Value,group=Type),colour=factor(Type))
    p + geom_line(data = data1,aes(fill = Type),position = "stack")
    p + geom_line(data = data1,aes(fill = Type),position = "stack")

Any advice on how to do this is greatly appreciated. Thanks.

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
jmcneill
  • 1
  • 1
  • 1
  • 3
    [Reproducible examples](http://stackoverflow.com/q/5963269/324364) are like booze around here. They loosen everyone up and _get them talking_. Hint hint hint. – joran May 03 '12 at 21:37

1 Answers1

5

In the absence of a reproducible example, I adapted this example from learnr:

library(ggplot2)
library(plyr)

data = read.table(text="Time    Type    Value
1   a   8
2   a   10
3   a   10
4   a   5
5   a   3
1   b   9
2   b   5
3   b   7
4   b   8
5   b   3
1   c   -3
2   c   -1
3   c   -5
4   c   -4
5   c   -7
1   d   -11
2   d   -3
3   d   -9
4   d   -6
5   d   -6", header=TRUE)

p <- ggplot(data, aes(x=Time))
p <- p + geom_line(subset = .(Type %in% c('a', 'b')),
                   aes(y=Value, colour = Type),
                   position = 'stack')
p <- p + geom_line(subset = .(Type %in% c('c', 'd')),
                   aes(y=Value, colour = Type),
                   position = 'stack')
p

To produce this:

Stacked line chart

And, for good measure, an area chart with a horizontal line:

p <- ggplot(data, aes(x=Time))
p <- p + geom_area(subset = .(Type %in% c('a', 'b')),
                   aes(y=Value, fill=Type),
                   position = 'stack')
p <- p + geom_area(subset = .(Type %in% c('c', 'd')),
                   aes(y=Value, fill = Type),
                   position = 'stack')
p <- p + geom_hline(yintercept=0)
p

area chart

Community
  • 1
  • 1
daedalus
  • 10,873
  • 5
  • 50
  • 71