Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Stacked area chart does not stack

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: enter image description here

My issue is, that the data does not stack correctly. I guess this could be because of the continuity of the data?

like image 898
lmz Avatar asked Sep 16 '26 14:09

lmz


1 Answers

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

enter image description here

like image 159
Roman Avatar answered Sep 18 '26 02:09

Roman



Donate For Us

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