【问题标题】:plot grouped data in R在 R 中绘制分组数据
【发布时间】:2013-03-21 11:38:06
【问题描述】:

我有一个分组数据如下:

group   x   y
group1  0   5
group4  0   5
group1  7   5
group4  0   5
group5  7   5
group1  7   5
group1  0   6
group2  0   6
group4  0   5
group2  0   5
group3  7   5

x 和 y 都是介于 0 和 7 之间的离散值。我想根据各自的 x 和 y 值将每个组数据放在 x-y 平面上。例如,我可以有多个 group1 点,所有这些都应该共享相同的颜色。如何在 R 中做到这一点?

【问题讨论】:

    标签: r graph plot


    【解决方案1】:

    数据:

    dat <- read.table(text = "group   x   y
    group1  0   5
    group4  0   5
    group1  7   5
    group4  0   5
    group5  7   5
    group1  7   5
    group1  0   6
    group2  0   6
    group4  0   5
    group2  0   5
    group3  7   5", header = TRUE)
    

    您可以使用出色的ggplot2 包来轻松绘图:

    library(ggplot2)
    ggplot(dat, aes(x = x, y = y, colour = group)) +
      geom_point() +
      facet_wrap( ~ group)
    

    在这里,我使用facet_wrap 为每个组创建构面。原则上这不是必需的,因为可以通过颜色来区分组的点。但在这种情况下,图中只有三个不同的位置。因此,如果将数据绘制在单个散点图中,则并非所有点都可见。

    【讨论】:

      【解决方案2】:

      使用 Sven 的回答中的数据,您还可以查看 lattice 包,它应该已经与您的 R 安装一起安装:

      library(lattice)
      # Each group in a separate mini plot
      xyplot(y ~ x | group, data = dat)
      # All groups in one plot, different colors for each group
      #   Not at all interesting with the example data you've provided
      xyplot(y ~ x, groups=dat$group, data = dat)
      

      以下是每个示例,其中包含更多数据:

      set.seed(1)
      mydf <- data.frame(
        group = sample(letters[1:4], 50, replace = TRUE),
        x = runif(50, 0, 7),
        y = runif(50, 0, 7)
      )
      xyplot(y ~ x, groups=mydf$group, data = mydf, 
             auto.key = list(corner = c(0, .98)), cex = 1.5)
      

      xyplot(y ~ x | group, data = mydf, 
             auto.key = list(corner = c(0, .98)), cex = 1.5)
      

      【讨论】:

        【解决方案3】:
        dd<- read.table("put the path to the txt file containing the data here", header=TRUE)
        g <- ggplot(dd, aes(as.factor(group)))
        g <- g + geom_point(aes(y=x), colour="red")
        g <- g + geom_point(aes(y=y), colour="green")
        g
        

        这将在单个图中为您提供 x 和 y 作为组的函数,如下所示。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-14
          • 2021-10-19
          • 2012-10-23
          • 1970-01-01
          • 2017-09-24
          相关资源
          最近更新 更多