【问题标题】:Scatter plot that shows all points with the same value显示具有相同值的所有点的散点图
【发布时间】:2015-09-14 13:03:00
【问题描述】:

如何在 R 中创建散点图,以便在某些类别中具有相同值的情况下显示所有点。除了数据点,我想在每个类别中都有平均值。

例如,如果我有两个变量的data set,其中一个(棉重百分比)是因子:

dat <- structure(list(`Tensile Strength` = c(12L, 19L, 17L, 7L, 25L, 
7L, 14L, 12L, 18L, 22L, 18L, 7L, 18L, 18L, 15L, 10L, 11L, 19L, 
11L, 19L, 15L, 19L, 11L, 23L, 9L), `Cotton weight percent` = c(20L, 
30L, 20L, 35L, 30L, 15L, 25L, 20L, 25L, 30L, 20L, 15L, 25L, 20L, 
15L, 35L, 35L, 25L, 15L, 25L, 35L, 30L, 35L, 30L, 15L)), .Names = c("Tensile Strength", 
"Cotton weight percent"), class = "data.frame", row.names = c(NA, 
-25L))

如何制作像这样的散点图:

这里,实心点是单个观察值,空心圆圈是观察到的平均拉伸强度。

【问题讨论】:

    标签: r plot statistics scatter-plot


    【解决方案1】:

    beeswarm 包为抖动点提供了一个不错的替代方案,而是提供了多种其他方法来排列您的点,使其看起来(除其他外)如下图所示:

    (see here for the beeswarm function used to create these plots)

    【讨论】:

      【解决方案2】:

      使用原生 R:

      plot(dat[,1]~dat[,2],ylab="Tensile Strength",xlab="Cotton weight percent",cex=1.5)
      points(sort(unique(dat[,2])),tapply(dat[,1],dat[,2],mean),pch=16,col=3,cex=1.5)
      

      如果你想显示重复的案例,你可以这样做:

      cwp=sort(unique(dat[,2]))
      ta=tapply(1:nrow(dat),list(dat[,2],dat[,1]),length)
      ft=function(v,x){#
        nm=as.numeric(colnames(v))
        do.call(rbind,lapply(1:length(nm),function(zv)if(v[zv]>1)
          cbind(rep(x,v[zv])+seq(.6,1.4,length.out=v[zv])-1,nm[zv]) else c(x,nm[zv])))
      }
      fd=lapply(1:nrow(ta),function(z)ft(t(ta[z,!is.na(ta[z,])]),cwp[z]))
      datf=do.call(rbind,fd)
      
      plot(datf[,2]~datf[,1],ylab="Tensile Strength",xlab="Cotton weight percent",cex=1.5)
      points(sort(unique(dat[,2])),tapply(dat[,1],dat[,2],mean),pch=16,col=3,cex=1.5)
      

      【讨论】:

      • 谢谢。这是我知道该怎么做,但它没有显示所有数据点(具有相同值的数据点)。
      【解决方案3】:

      这可以在 ggplot2 中使用 geom_jitterstat_summary 完成。具体来说,geom_jitter 会给你图表上的黑点:

      library(ggplot2)
      ggplot(mtcars, aes(factor(cyl), mpg)) +
          geom_jitter(position = position_jitter(width = .1))
      p
      

      (“抖动”是在 x 轴方面添加一些噪声,如您的示例中所示)。

      然后stat_summary 层可让您为每个 x 值的平均值添加一个点(我已将其放大为红色):

      ggplot(mtcars, aes(factor(cyl), mpg)) +
          geom_jitter(position = position_jitter(width = .1)) +
          stat_summary(fun.y = "mean", geom = "point", color = "red", size = 3)
      

      【讨论】:

      • @LegalizeIt 很好,你是怎么得到棉花重量百分比的? (手动?)
      • @LegalizeIt 我错过了 OP 发布了数据集,谢谢!!
      • 谢谢!我在我的数据集上尝试了它并且它有效。它与我附加的散点图相当,但我想改进一件事 - 相同值的点不仅沿 x 轴移动,而且沿 y 轴移动。我希望它们在 y 轴上具有相同的值,但仅在 x 轴上分开。你知道我该怎么做吗?
      • @user23709 当然可以,只需将geom_jitter(position = ...) 更改为geom_point()
      猜你喜欢
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 2021-01-25
      相关资源
      最近更新 更多