Reputation: 17
I want to create a 100% stacked area plot in R Studio. For my other graphs, I am using ggplot2. I know this is an easy question and there are resources online, but I just cant do it.
time is supposed to be on the x-axis. And the data is in the column 'example_col'. As you see, these values are seperated by comma and each row has a sum of 1.
time example_col
00:00:00 0.018,0.600,0.263,0.119,0.000
00:05:00 0.007,0.621,0.207,0.120,0.045
00:10:00 0.000,0.665,0.265,0.069,0.000
00:15:00 0.008,0.640,0.242,0.109,0.000
00:20:00 0.021,0.529,0.287,0.114,0.049
00:25:00 0.000,0.579,0.262,0.159,0.000
00:30:00 0.021,0.714,0.265,0.000,0.000
... ...
I can separate the data into seperate columns using substr(). I have found these solutions, but I cant make it work:
ggplot2 plotting a 100% stacked area chart
Reshaping data.frame from wide to long format
How do I do it?
Thanks so much!
Upvotes: 0
Views: 235
Reputation: 23737
I think this is mainly a reading data and class conversion problem.
Here one way (comments in the code)
library(tidyverse)
df<-read.table(text = "
0.018,0.600,0.263,0.119,0.000
0.007,0.621,0.207,0.120,0.045
0.000,0.665,0.265,0.069,0.000
0.008,0.640,0.242,0.109,0.000
0.021,0.529,0.287,0.114,0.049
0.000,0.579,0.262,0.159,0.000
0.021,0.714,0.265,0.000,0.000")
df %>%
## split the data
separate(V1, into = paste0("V", 1:5), sep = ",") %>%
## convert the values to numeric
## add an identifier column for the rows, this will be used for your x position
mutate(across(everything(), as.numeric),
group = seq_along(V1)) %>%
## make long
pivot_longer(starts_with("V")) %>%
## now plot
ggplot() +
geom_col(aes(as.character(group), value, fill = name))
Upvotes: 2