I have data which I want to plot as a stacked area plot. On the x-axis I have data which is continuous and on the y axis I have continuous data which I prepare to be cumulative. This is the code I am using with some dummy data:
library(data.table)
library(ggplot2)
set.seed(1)
dt <- data.table(var=sample(1:6,1000,replace=TRUE),xdata=runif(1000),ydata=runif(1000))
setorder(dt, var, xdata)
dt$cumydata <- dt[,
cumsum(ydata),
by = .(var)]$V1/sum(dt$ydata)
ggplot(dt, aes(x = xdata, y = cumydata, fill = as.factor(var))) +
geom_area(position = "stack")
Here is the output plot:

My issue is, that the data does not stack correctly. I guess this could be because of the continuity of the data?
For a stacked area chart the x values as well as the number of occurences must be the same. So changing your sample data to this will give you the expected output:
set.seed(1)
dt <- data.table(ydata=runif(1002))
dt$var <- rep(1:6, each=167)
dt$xdata <- rep(runif(167), 6)
setorder(dt, var, xdata)
dt$cumydata <- dt[,
cumsum(ydata),
by = .(var)]$V1/sum(dt$ydata)
ggplot(dt,aes(x = xdata, y = cumydata, fill = as.factor(var))) +
geom_area(position = "stack")

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With