-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLecture2.R
More file actions
75 lines (66 loc) · 2.05 KB
/
Copy pathLecture2.R
File metadata and controls
75 lines (66 loc) · 2.05 KB
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
70
71
72
73
74
75
#Lecture 2
#minghaowu_2015@163.com
setwd("~/documents/R programming/ggplot2")
library(ggplot2)
attach(mpg)
head(mpg)
#Review
qplot(displ, hwy, data = mpg, colour = factor(cyl))
qplot(displ, hwy, data = mpg,
colour = factor(cyl),
geom=c("smooth","point"),
method="lm")
qplot(displ, hwy, data=mpg, facets = . ~ year) + geom_smooth()
#Save
p = qplot(displ, hwy, data = mpg, colour = factor(cyl))
summary(p)
save(p, file = "plot.rdata")
load("plot.rdata")
ggsave("plot.png", width = 5, height = 5)
#Build a plot layer by layer
p = ggplot(diamonds, aes(carat, price, colour = cut))
p
p = p + layer(geom = "point")
#ggplot(diamonds, aes(carat, price, colour = cut)) + layer(geom = "point")
p
#layer(geom, geom_params, stat, stat_params, data, mapping, position)
p <- ggplot(diamonds, aes(x = carat))
p <- p + layer(
geom = "bar",
geom_params = list(fill = "steelblue"),
stat = "bin",
stat_params = list(binwidth = 0.5)
)
p
#basic form
#geom_XXX(mapping, data, ..., geom, position)
#stat_XXX(mapping, data, ..., stat, position)
#Example 1
ggplot(msleep, aes(sleep_rem / sleep_total, awake)) + geom_point()
#is equivalent to
qplot(sleep_rem / sleep_total, awake, data = msleep)
#Example 2
qplot(sleep_rem / sleep_total,
awake, data = msleep,
geom = c("point", "smooth"))
#is equivalent to
ggplot(msleep, aes(sleep_rem / sleep_total, awake)) + geom_point() + geom_smooth()
#is equivalent to
plot = ggplot(msleep, aes(sleep_rem / sleep_total, awake))
plot = plot + geom_point() + geom_smooth()
plot
#Example 3 (cont.)
bestfit = geom_smooth(method = "lm",
se = T,
colour = "steelblue",
alpha=0.5,
size = 2)
qplot(sleep_rem, sleep_total, data = msleep) + bestfit
qplot(displ, hwy, data=mpg, facets = . ~ year) + bestfit
#Transform the data in the plot using %+%
p = ggplot(mtcars, aes(mpg, wt, colour = cyl)) + geom_point(size=5)
p
mtcars = transform(mtcars, mpg = mpg ^ 2)
p %+% mtcars
#Aesthetic mappings
qplot(color, price, data = diamonds, geom = "boxplot",fill=I("blue"))