Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

r - Line graph from replicate data with error bars

Im trying to make a growth curve with 2 variables on the same plot (Media1 and Media2). I have 3 time points (T1,T2...) and each time point was repeated 3 times (R1,R2,R3). I need to average the replicates and make a line graph with error bars. Example of the data:

Time Replicate      Media1     Media2
1       T0        R1 0.013733333 0.03770000
2       T0        R2 0.008233333 0.03690000
3       T0        R3 0.013333333 0.03760000
4       T1        R1 0.018166667 0.03680000
5       T1        R2 0.013466667 0.03570000
6       T1        R3 0.018366667 0.03700000
7       T2        R1 0.028066667 0.04420000
8       T2        R2 0.022966667 0.04400000
9       T2        R3 0.027866667 0.04420000
10      T3        R1 0.041333333 0.05536667
11      T3        R2 0.033433333 0.05476667
12      T3        R3 0.039833333 0.05446667

I have figured out how to average the replicates using this:

.colMeans(df$Media1, 3, length(df$Media1) / 3)

And I know how to plot it in ggplot. I just can't figure out how to get error bars on the line graph from the original non-averaged data.

Thanks for any help

question from:https://stackoverflow.com/questions/65645858/line-graph-from-replicate-data-with-error-bars

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you reshape your data so that it is in the long format, you can use stat = "summary" to calculate relevant statistics from the data. What statistics are calculated depend on the fun/fun.data argument.

library(ggplot2)

df <- read.table(text = "Time Replicate      Media1     Media2
1       T0        R1 0.013733333 0.03770000
2       T0        R2 0.008233333 0.03690000
3       T0        R3 0.013333333 0.03760000
4       T1        R1 0.018166667 0.03680000
5       T1        R2 0.013466667 0.03570000
6       T1        R3 0.018366667 0.03700000
7       T2        R1 0.028066667 0.04420000
8       T2        R2 0.022966667 0.04400000
9       T2        R3 0.027866667 0.04420000
10      T3        R1 0.041333333 0.05536667
11      T3        R2 0.033433333 0.05476667
12      T3        R3 0.039833333 0.05446667")

df <- tidyr::pivot_longer(df, c("Media1", "Media2"))

ggplot(df, aes(Time, value, colour = name)) +
  geom_jitter(width = 0.2) +
  geom_line(aes(group = name), stat = "summary", fun = mean) +
  geom_errorbar(stat = "summary", fun.data = function(x) {
    data.frame(ymin = mean(x) - sd(x), ymax = mean(x) + sd(x))
  }, width = 0.1)

Created on 2021-01-09 by the reprex package (v0.3.0)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...