Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

r - qqline in ggplot2 with facets

This question showed how to make a qqplot with a qqline in ggplot2, but the answer only seems to work when plotting the entire dataset in a single graph.

I want a way to quickly compare these plots for subsets of my data. That is, I want to make qqplots with qqlines on a graph with facets. So in the following example, there would be lines for all 9 plots, each with their own intercept and slope.

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)

facet data

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may try this:

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)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...