0

I would like to create a stacked chart using the ggplot2 library in R to create shaded areas (for Bananas and Kiwi). The problem is that data (Bananas, Kiwi) comes from two separate functions, thus there are two data objects.

plot(t, Bananas, type="l", xlab = "",xlim=c(0,70), ylim=c(0,1) lty=1)
lines(t, Kiwi, lty=2)

How can I implement two "data" objects in the ggplot?

p <- ggplot(data= , aes(x= t, group=, fill=)) + geom_density(adjust=1.5, position="fill") +
    theme_ipsum()
Maël
  • 45,206
  • 3
  • 29
  • 67
Oksana
  • 25
  • 4

1 Answers1

0

A good idea is to join the two data sets:

library(tidyverse)

#first create the data 
df_bananas <- data.frame(t=c(1:4),Bananas=c(2,4,8,10))
df_kiwis <- data.frame(t=c(2:4),Kiwis=c(3,6,9))

# then join the two data frames. Note that the fruit data are in "value" 
df_fruits <- full_join(df_bananas,df_kiwis)
head(df_fruits)

#ggplot2 likes "long" data frames i.e. the plotted data should be all in one column:
df_fruits_l <- pivot_longer(df_fruits, names_to = "fruits", cols =c(Bananas, Kiwis))
head(df_fruits_l) 

ggplot(data=df_fruits_l , aes(x= t, y=value, colour = fruits, fill= fruits))+
  geom_area(position = 'stack')+
  theme_bw()

enter image description here

For more on join, see here