我使用ggplot创建了一个NMDS图,其中椭圆对应于我的不同组(我有3年两次处理;不同的处理具有不同的椭圆轮廓和符号,而不同的年份具有不同的椭圆颜色和符号颜色)。
这是我的代码:
ggplot(nmds, aes(x=nmds1, y=nmds2, col=group)) +
geom_point(aes(shape=group)) +
stat_ellipse(aes(x = nmds1,y=nmds2, fill=group, linetype=group), geom="polygon", alpha=0.2, segments=201) +
scale_linetype_manual(values=c(1,2,1,2,1,2)) + scale_fill_manual(values=c("maroon","maroon","steelblue2","steelblue2","seagreen", "seagreen")) + scale_colour_manual(values=c("maroon","maroon","steelblue2","steelblue2","seagreen", "seagreen")) +
scale_shape_manual(values=c(1,2,1,2,1,2))
我想看看我的一种治疗的三个椭圆是否明显小于另一种治疗的三个椭圆。如何计算他们的面积?然后,我可以使用t检验来检验显着差异。
这是我以前用椭圆颜色将样本分开的方法,但是很容易对其进行调整以使其适用于颜色和形状的组合。只需通过添加另一个为唯一形状选择的嵌套循环来调整子集选项。
此代码基于此处的答案:How to calculate the area of ellipse drawn by ggplot2?
# Get ellipse coordinates from plot
pb = ggplot_build(data)
el = pb$data[[2]][c("colour",
#"shape",
"x",
"y")] #If you separated by shape as well then include it here as well and then separate by shape as well
#Make an empty dataframe where your data is going to end up
ellipseAreaList = data.frame()
#Identify unique groups (in my case colour)
group_list = unique(el$colour)
#Start the loop
for (i in 1:length(group_list)) {
#Subset to separate into individual ellipse groups - if you used shape in addition to colour you'll want to change this as well
Object = subset(el,
colour == group_list[i])
#Remove grouping column
Object = Object[-1]
# Center of ellipse
ctr = MASS::cov.trob(Object)$center
# Calculate distance to center from each point on the ellipse
dist2center <- sqrt(rowSums((t(t(Object)-ctr))^2))
# Calculate area of ellipse from semi-major and semi-minor axes.
# These are, respectively, the largest and smallest values of dist2center.
value = pi*min(dist2center)*max(dist2center)
#Store in the area list
ellipseAreaList = rbind(ellipseAreaList, data.frame(group_list[i], value))
}