William Liu
William Liu

Reputation: 339

plot vertical stacking line based on time point in r

My df is like this:

TEST ID  C1  C2  C3  C4  C5  C6  C7
A    22 112 112 118 121 124 NA  NA
B    22  77 89  85  89  88  95  100
C    22  67 85  76  77  77  84  92
D    22  58 81  73  75  79  84  95

C1, C2, C3... represents different time points. Each row represents a different test In this df, student 22 has been tested for 5 times on TEST A, and 7 times on test B,C and D.

I intend to use ggplot2 to create a vertically stacked line graph with the x-axis as the four tests, the y-axis as scores, and the vertical stacking being based on time point. Can anyone help me?

Thanks!

Upvotes: 1

Views: 206

Answers (1)

akrun
akrun

Reputation: 887501

May be this helps

library(tidyr)
library(ggplot2)

gather(df, Var, Val, C1:C7) %>% 
            filter(!is.na(Val)) %>%
            ggplot(. , aes(x=TEST, y=Val, fill=Var))+
            geom_bar(stat='identity')

Update

These are some options.

df1 <- gather(df, Var, Val, C1:C7) %>% 
                               filter(!is.na(Val))

ggplot(df1, aes(x=TEST, y=Val, colour=Var))+
                geom_area(aes(fill=Var), position='stack')

Or

 ggplot(df1, aes(x=as.numeric(factor(TEST)), y=Val, fill=Var)) +
                                      geom_area(position='stack')

Or

 group_by(df1, TEST) %>%
    mutate(Val1=cumsum(Val)) %>%
    ggplot(., aes(x=as.numeric(factor(TEST)), y=Val1, color=Var)) + 
    geom_line() + 
    xlab('TEST') +
    ylab('Score') +
    scale_x_discrete(breaks=as.numeric(factor(df2$TEST)), 
             labels=df2$TEST)

data

df <- structure(list(TEST = c("A", "B", "C", "D"), ID = c(22L, 22L, 
22L, 22L), C1 = c(112L, 77L, 67L, 58L), C2 = c(112L, 89L, 85L, 
81L), C3 = c(118L, 85L, 76L, 73L), C4 = c(121L, 89L, 77L, 75L
), C5 = c(124L, 88L, 77L, 79L), C6 = c(NA, 95L, 84L, 84L), C7 = c(NA, 
100L, 92L, 95L)), .Names = c("TEST", "ID", "C1", "C2", "C3", 
"C4", "C5", "C6", "C7"), class = "data.frame", row.names = c(NA, -4L))

Upvotes: 2

Related Questions