-1

I realize this question has been asked previously and it has been suggested to use ggplot, lattice etc. My question relates to adding the mean value onto boxplot according to a categorical variable.

Here is my code and it does not work:

STEP 1: I created a vector using tapply to get the mean value of bmi z-scores at age 4 years according to maternal obesity group:

means <- tapply(therapy$zbmi_4,therapy$Gruppe,mean,na.rm=TRUE) # calculate means

The output looks like:

>means
Normal-weight         Obese 
-0.03207792        0.60130081

STEP 2: I created a simple boxplot of bmi z-scores at age 4 years according to maternal obesity group:

plot(therapy$Gruppe,therapy$zbmi_4,
xlab = 'Maternal BMI groups',
ylab = 'Offspring BMI z-scores at 4 years',
cex.lab=1.5, cex.axis=1.4, cex.main=1.6, cex.sub=1.5,
col=c("white","grey"), main="Effect of maternal obesity",
pch=16,cex=1)
points(x=therapy$Gruppe,y=means,pch=19, col="red") # add means
legend("topleft", legend=c("P-value <0.0001"), bty = "n", cex=1.5)

The output looks like this (without points) <code>x=therapy$Gruppe,y=means,pch=19, col="red")</code>

The error message is:

>points(x=therapy$Gruppe,y=means,pch=19, col="red", type="l") # add means
Error in xy.coords(x, y) : 'x' and 'y' lengths differ

I totally understand this issue. Since, there are 949 observations and only 2 means.

> length(therapy$Gruppe)
[1] 949
> length(means)
[1] 2

Now, am I thinking too much or is there a very simple way of adding a "dot" in each of the box plot for mean bmi z-score according to maternal group of obesity (normal-weight versus obese). I would really appreciate any sort of help and suggestions.

Thank you so much in advance

Adam Quek
  • 6,973
  • 1
  • 17
  • 23

1 Answers1

0

Just use x = 1:length(means) (according to your number of group) in points(). Here is an example with iris since you did not provide data.

data(iris)

means <- tapply(iris$Sepal.Length, iris$Species, mean)

plot(iris$Species, iris$Sepal.Length)
points(x = 1:length(means), y = means, pch = 10)

enter image description here

scoa
  • 19,359
  • 5
  • 65
  • 80