'How to reverse second object in stacked ggplot?
How can I reverse the variable in my ggplot, so to variable 'Bananas' starts from 1 and Kiwis from 0, and the gray area in the middle?
p <- ggplot(data=df, aes(x=t, y=value, colour=fruits, fill=fruit))+
geom_area(position = 'stack')+
theme_bw()

Solution 1:[1]
We don't have your data, so let's reproduce it:
df <- data.frame(t = rep(0:100, 2),
value = c(2 * (0.95/(1 + exp(-0.1 * (0:100))) - 0.475),
2 * (0.05/(1 + exp(-0.1 * (0:100))) - 0.025)),
fruits = factor(rep(c("Bananas", "Kiwis"), each = 101),
c("Kiwis", "Bananas")))
ggplot(data = df, aes(x = t, y = value, colour = fruits, fill = fruits)) +
geom_area(position = 'stack')
To get the Kiwi at the top and bananas at the bottom, you can't use geom_area - you will need to use geom_ribbon, and manipulate the data to get the top and bottom edges of your ribbon:
df$min <- 0
df$max <- 1
df$min[df$fruits == "Kiwis"] <- 1 - df$value[df$fruits == "Kiwis"]
df$max[df$fruits == "Bananas"] <- df$value[df$fruits == "Bananas"]
ggplot(data = df, aes(x = t, y = value, colour = fruits, fill = fruits)) +
geom_ribbon(aes(ymin = min, ymax = max))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allan Cameron |


