2017-05-22 67 views
-1

我意識到這個問題以前已經被問到過,並且有人建議使用ggplot,lattice等。我的問題涉及根據分類變量將平均值添加到boxplot上。添加平均值時出現箱子打印錯誤

這裏是我的代碼,它不工作:

STEP 1:

:我使用tapply根據產婦肥胖組的年齡獲得BMI z分數的平均值值4年內製作矢量
means <- tapply(therapy$zbmi_4,therapy$Gruppe,mean,na.rm=TRUE) # calculate means 

輸出看起來像:

>means 
Normal-weight   Obese 
-0.03207792  0.60130081 

STEP 2:我的年齡創造了BMI z分數的簡單箱圖4年根據產婦肥胖組:

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>

的錯誤信息是:

>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 

我完全理解這個問題。因爲有949個觀測值,只有2個平均值。

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

現在,是我想得太多,還是有在每個箱形圖根據對產婦組肥胖(體重正常的平均BMI z分數的增加一個「點」的一個非常簡單的方法肥胖)。我真的很感激任何幫助和建議。

非常感謝你提前

回答

0

只需使用x = 1:length(means)(根據您的組數)points()。由於您沒有提供數據,因此以iris爲例。

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