Remove objects currently held in the environment
rm(list=ls())
We will continue to use the iris
dataset, and follow on directly from the previous lecture on barplots to visualise the same data using errorbar plots.
Use an errorbar plot to show the data
# specify a 1x1 panel plot
par(mfrow=c(1,1))
Calculate the means of the groups using tapply()
mu <- tapply(iris$Petal.Length, iris$Species, mean)
Here I write my own function to calculate the 95% confidence intervals, see
CI95 <- function (x) {return( 1.96 * sqrt( var(x) / length(x) ) )}
# calculate the error for ecah group (espilon or eps as named)
eps <- tapply(iris$Petal.Length,iris$Species,CI95)
plot(1:3,mu,xlim=c(0,4),ylim=c(1,7),pch=20, las=1, bty="L",
xlab="Species", ylab="Petal Length (cm)")
arrows( x0 = 1:3, x1 = 1:3,
y0 = mu + eps, y1 = mu - eps,
code = 3, length = 0.1, angle = 90)
par(mfrow=c(1,1))
Calculate the means of the groups
# mu <- tapply(iris$Petal.Length,iris$Species,mean)
#
# CI95 <- function (x) {return(1.96*sd(x)/sqrt(length(x)))}
#
# se <- tapply(iris$Petal.Length,iris$Species,CI95)
plot(1:3, mu, xlim = c(0,4), ylim = c(1,7),
pch = 20, las = 1, bty = "L", xaxt ="n",
xlab = "Species", ylab = "Petal Length (cm)")
axis(1, at = 1:3, levels(iris$Species))
arrows( x0 = 1:3, x1 = 1:3,
y0 = mu + eps, y1 = mu - eps,
code = 3, length = 0.1, angle = 90)
axis(side, at=, labels=, pos=, lty=, col=, las=, tck=, …)
Side option in axis function - an integer indicating the side of the graph to draw the axis (1=bottom, 2=left, 3=top, 4=right) At - a numeric vector indicating where tic marks should be drawn
Do not forget to install ggplot package before executing this code.
library(tidyverse) # load package with ggplot
## Loading tidyverse: ggplot2
## Loading tidyverse: tibble
## Loading tidyverse: tidyr
## Loading tidyverse: readr
## Loading tidyverse: purrr
## Loading tidyverse: dplyr
## Conflicts with tidy packages ----------------------------------------------
## filter(): dplyr, stats
## lag(): dplyr, stats
p1 <- ggplot(iris, aes(Species, Petal.Length)) +
stat_summary(fun.y = mean, geom = "point") +
coord_cartesian(ylim = c(0, 6)) + labs(y = "Petal length (cm)") +
stat_summary(fun.data = mean_se, geom = "errorbar",
width = 0.1, size = 0.8, colour = "blue")
print(p1)