[R] How to add error bars to lattice xyplot

Luigi Marongiu m@rong|u@|u|g| @end|ng |rom gm@||@com
Mon Oct 11 14:11:06 CEST 2021


Hello,
I am trying to plot data using lattice. The basic plot works:
```
Substance = rep(c("A", "B", "C", "D"),4)
Concentration = rep(1:4,4),
Value = c(62.80666667, 116.26333333,  92.26000000,   9.87333333,  14.82333333,
          92.37333333, 98.95666667,   1.48333333,   0.64666667,  50.66000000,
          25.75333333,   0.69000000, 0.21666667,   7.40666667,   6.92000000,
          0.06333333)
df = data.frame(Substance, Concentration, Value, stringsAsFactors = FALSE)
Value = c(15.2974126, 16.3196089, 57.4294280,  9.1943370, 20.5567321,
14.0874424,
       38.3626672, 0.3780653,  0.4738495, 37.9124874, 16.2473916,  0.7218726,
       0.2498666,  8.4537585, 10.8058456,  0.1096966)
dfsd = data.frame(Substance, Concentration, Value, stringsAsFactors = FALSE)

library(lattice)
COLS = c("gold", "forestgreen", "darkslategray3", "purple")
xyplot(Value ~ Concentration,
       group = Substance, data = df,
       pch = 16, cex = 1.2, type = "b",
       xlab=expression(bold(paste("Concentration (", mu, "M)"))),
       ylab=expression(bold("Infection rate")),
       col=COLS,
       scales = list(x = list(log = 10, at=c(unique(df$Concentration))
       )
       ),
       key = list(space="top", columns=4, col = "black",
                  points=list(pch=c(16, 16, 16, 16),
                              col=COLS,
                              text=list(c("6-PN", "8-PN", "IX", "XN")
                              )
                  )
       )

)
```
but how do I add the error bars?
I tried with
```
xyplot(Value ~ Concentration,
       group = Substance, data = df,
       pch = 16, cex = 1.2, type = "b",
       xlab=expression(bold(paste("Concentration (", mu, "M)"))),
       ylab=expression(bold("Infection rate")),
       col=COLS,
       scales = list(x = list(log = 10, at=c(unique(df$Concentration))
       )
       ),
       key = list(space="top", columns=4, col = "black",
                  points=list(pch=c(16, 16, 16, 16),
                              col=COLS,
                              text=list(c("6-PN", "8-PN", "IX", "XN")
                              )
                  )
       ),
       panel = function (x,y,) {
         panel.segments(x0 = df$Concentration, x1 = df$Concentration,
                        y0 = df$Value - dfsd$Value,
                        y1 = df$Value + dfsd$Value,
                        col = COLS)
       }

)
```
but the bars are plotted outside the graph.
What is the correct syntax? can I use raw data instead of making the
mean and std dev separately?
Thanks

-- 
Best regards,
Luigi



More information about the R-help mailing list