-
Notifications
You must be signed in to change notification settings - Fork 2k
/
geom-smooth.r
69 lines (54 loc) · 2.14 KB
/
geom-smooth.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
GeomSmooth <- proto(Geom, {
draw <- function(., data, scales, coordinates, ...) {
ribbon <- transform(data, colour = NA)
path <- transform(data, alpha = 1)
gList(
tryNULL(GeomRibbon$draw(ribbon, scales, coordinates)),
GeomPath$draw(path, scales, coordinates)
)
}
objname <- "smooth"
desc <- "Add a smoothed condition mean."
icon <- function(.) {
gTree(children=gList(
polygonGrob(c(0, 0.3, 0.5, 0.8, 1, 1, 0.8, 0.5, 0.3, 0), c(0.5, 0.3, 0.4, 0.2, 0.3, 0.7, 0.5, 0.6, 0.5, 0.7), gp=gpar(fill="grey60", col=NA)),
linesGrob(c(0, 0.3, 0.5, 0.8, 1), c(0.6, 0.4, 0.5, 0.4, 0.6))
))
}
guide_geom <- function(.) "smooth"
default_stat <- function(.) StatSmooth
required_aes <- c("x", "y")
default_aes <- function(.) aes(colour="#3366FF", fill="grey60", size=0.5, linetype=1, weight=1, alpha=0.4)
draw_legend <- function(., data, params, ...) {
data <- aesdefaults(data, .$default_aes(), list(...))
data$fill <- alpha(data$fill, data$alpha)
if (is.null(params$se) || params$se) {
gTree(children = gList(
rectGrob(gp = gpar(col = NA, fill = data$fill)),
GeomPath$draw_legend(data, ...)
))
} else {
GeomPath$draw_legend(data, ...)
}
}
examples <- function(.) {
# See stat_smooth for examples of using built in model fitting
# if you need some more flexible, this example shows you how to
# plot the fits from any model of your choosing
library(ggplot2)
qplot(wt, mpg, data=mtcars, colour=factor(cyl))
model <- lm(mpg ~ wt + factor(cyl), data=mtcars)
grid <- with(mtcars, expand.grid(
wt = seq(min(wt), max(wt), length = 20),
cyl = levels(factor(cyl))
))
grid$mpg <- stats::predict(model, newdata=grid)
qplot(wt, mpg, data=mtcars, colour=factor(cyl)) + geom_line(data=grid)
# or with standard errors
err <- stats::predict(model, newdata=grid, se = TRUE)
grid$ucl <- err$fit + 1.96 * err$se.fit
grid$lcl <- err$fit - 1.96 * err$se.fit
qplot(wt, mpg, data=mtcars, colour=factor(cyl)) +
geom_smooth(aes(ymin = lcl, ymax = ucl), data=grid, stat="identity")
}
})