【问题标题】:How to compute area of multiple ellipses in ggplot?如何计算ggplot中多个椭圆的面积?
【发布时间】:2019-08-06 10:56:58
【问题描述】:

我使用 ggplot 创建了一个 NMDS 图,椭圆对应于我的不同组(我有三年和两次治疗;不同的治疗有不同的椭圆轮廓和符号,而不同的年份有不同的椭圆颜色和符号颜色)。

这是我的代码:

  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 检验来测试显着差异。

【问题讨论】:

  • 您好,欢迎来到 SO!如果您提供一个可重现的示例,将会有所帮助(此页面可能会有所帮助:stackoverflow.com/questions/5963269/…)。您的代码不可重现,因为我们不知道 nmds 的样子。
  • 计算椭圆的面积不会让您运行 t 检验。也许使用vegan::betadisper 更直接地检验你的假设
  • 我得到 p=0.04,在 5% 时非常显着。这足以“证明”其中一种治疗方法中的较小椭圆吗?另外,你知道这在生态学上是如何解释的吗?

标签: r ggplot2 ellipse


【解决方案1】:

这是我用来按椭圆颜色分离样本的方法,但它应该很容易适应颜色和形状的组合。只需通过添加另一个选择独特形状的嵌套循环来调整子集选项。

此代码基于此处的答案: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))
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2013-05-09
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    相关资源
    最近更新 更多