0

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

Fruit ggplot2

zx8754
  • 52,746
  • 12
  • 114
  • 209
Oksana
  • 25
  • 4
  • Please make the question reproducible by including the output of `dput(df)`. [Link for guidance on asking questions](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Peter Feb 25 '22 at 14:49
  • Make fruits column a factor, and set the level orders to Kiwis, Bananas. Otherwise it is sorted alphabetically and Bananas plots first at the bottom. – zx8754 Feb 25 '22 at 15:04

1 Answers1

0

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

enter image description here

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

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87