[R] How to add error bars to a line plot with ggplot2?

Luigi Marongiu m@rong|u@|u|g| @end|ng |rom gm@||@com
Fri Jul 14 18:33:38 CEST 2023


Hello,
I am measuring a certain variable at given time intervals and
different concentrations of a reagent. I would like to make a scatter
plot of the values, joined by a line to highlight the temporal
measure.
I can plot this all right. Now, since I have more than one replicate,
I would like to add he error bars.
I prepared  a dataframe with the mean measures and a column with the
standard deviations, but when I run the code, I get the error:
```
Error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (20): colour
Run `rlang::last_trace()` to see where the error occurred.
```
I am missing something, but what?
Thank you


WORKING EXAMPLE
```
measTime    = c(1    ,2    ,4    ,24    ,48    ,1    ,2    ,4    ,24
 ,48    ,1    ,2    ,4    ,24    ,48    ,1    ,2    ,4    ,24    ,48)
conc    = c(0.25    ,0.25    ,0.25    ,0.25    ,0.25    ,1.12    ,1.12
   ,1.12    ,1.12    ,1.12    ,2.5    ,2.5    ,2.5    ,2.5    ,2.5
,25    ,25    ,25    ,25    ,25)
varbl    = c(0.0329999999999999    ,0.27    ,0.0785    ,0.1015
,-0.193    ,0.048    ,0.113    ,0.1695    ,-0.775    ,0.464    ,-0.257
   ,-0.154    ,-0.3835    ,-1.23    ,-0.513    ,1.3465    ,1.276
,1.128    ,-2.56    ,-1.813)
stdDev    =c(0.646632301492381    ,0    ,1.77997087991162
,0.247683265482349    ,0    ,0.282901631902917    ,0
,0.273086677326693    ,1.03807578400295    ,0    ,0.912213425319609
,0    ,1.64371621638287    ,2.23203614068709    ,0    ,0.2615396719429
   ,0    ,0.54039985196149    ,2.15236180353893    ,0)
df = data.frame(Time=measTime, mM=conc, ddC=varbl, SD=stdDev)
library(ggplot2)
COLS = c("green", "red", "blue", "yellow")
  ggplot(df,
         aes(x=Time, y=ddC, colour=mM, group=mM)) +
  geom_line(aes(x=Time, y=ddC, colour=mM, group=mM)) +
  geom_errorbar(aes(x=Time, ymin=ddC-SD, ymax=ddC+SD, colour=mM, group=mM),
                width=.1, colour=COLS) +
  geom_point(size=6) +
  scale_colour_manual(values = COLS) +
  ggtitle("Exposure") +
  xlab(expression(bold("Time (h)"))) +
  ylab(expression(bold("Value"))) +
  geom_hline(aes(yintercept=0)) +
  theme_classic()
  ```



More information about the R-help mailing list