【问题标题】:qqline in ggplot2 with facetsggplot2中的qqline与方面
【发布时间】:2013-10-25 21:31:29
【问题描述】:

This 问题展示了如何在 ggplot2 中使用 qqline 制作 qqplot,但答案似乎仅在将整个数据集绘制在单个图表中时才有效。

我想要一种方法来快速比较我的数据子集的这些图。也就是说,我想在带有刻面的图上制作带有 qqlines 的 qqplots。所以在下面的例子中,所有 9 个图都有线,每个图都有自己的截距和斜率。

df1 = data.frame(x = rnorm(1000, 10),
                 y = sample(LETTERS[1:3], 100, replace = TRUE),
                 z = sample(letters[1:3], 100, replace = TRUE))

ggplot(df1, aes(sample = x)) +
  stat_qq() +
  facet_grid(y ~ z)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你可以试试这个:

    library(plyr)
    
    # create some data
    set.seed(123)
    df1 <- data.frame(vals = rnorm(1000, 10),
                      y = sample(LETTERS[1:3], 1000, replace = TRUE),
                      z = sample(letters[1:3], 1000, replace = TRUE))
    
    # calculate the normal theoretical quantiles per group
    df2 <- ddply(.data = df1, .variables = .(y, z), function(dat){
                 q <- qqnorm(dat$vals, plot = FALSE)
                 dat$xq <- q$x
                 dat
    }
    )
    
    # plot the sample values against the theoretical quantiles
    ggplot(data = df2, aes(x = xq, y = vals)) +
      geom_point() +
      geom_smooth(method = "lm", se = FALSE) +
      xlab("Theoretical") +
      ylab("Sample") +
      facet_grid(y ~ z)
    

    【讨论】:

      【解决方案2】:

      无缘无故,这是同一事物的dplyr(在提出此问题时不存在)版本。为了同行评审和比较,我将提供生成数据集的代码,以便您进一步检查它们。

      # create some data
      set.seed(123)
      df1 <- data.frame(vals = rnorm(10, 10),
                        y = sample(LETTERS[1:3], 1000, replace = TRUE),
                        z = sample(letters[1:3], 1000, replace = TRUE))
      
      #* Henrik's plyr version
      library(plyr)
      df2 <- plyr::ddply(.data = df1, .variables = .(y, z), function(dat){
                   q <- qqnorm(dat$vals, plot = FALSE)
                   dat$xq <- q$x
                   dat
      }
      )
      
      detach("package:plyr")
      
      
      #* The dplyr version
      library(dplyr)
      qqnorm_data <- function(x){
        Q <- as.data.frame(qqnorm(x, plot = FALSE))
        names(Q) <- c("xq", substitute(x))
        Q
      }
      
      df3 <- df1 %>%
        group_by(y, z) %>%
            do(with(., qqnorm_data(vals)))
      

      可以使用来自 Henrik 的相同代码进行绘图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-12
        • 1970-01-01
        • 2021-12-19
        • 1970-01-01
        • 2015-05-20
        • 2015-05-19
        相关资源
        最近更新 更多