ggplot2: Grammar


Dữ liệu

head(mpg)
## [1] 18 15 18 16 17 15

Xây dựng biểu đồ điểm

qplot(displ, hwy, data = mpg, colour = factor(cyl))
## Error: ggplot2 doesn't know how to deal with data of class numeric
qplot(displ, hwy, data=mpg, colour=factor(cyl), geom="line")
## Error: ggplot2 doesn't know how to deal with data of class numeric
qplot(displ, hwy, data=mpg, colour=factor(cyl), geom="bar", 
stat="identity", position = "identity")
## Error: ggplot2 doesn't know how to deal with data of class numeric
# A complex plot without name
qplot(displ, hwy, data=mpg, colour=factor(cyl)) +
geom_smooth(data = subset(mpg, cyl != 5), method="lm")
## Error: ggplot2 doesn't know how to deal with data of class numeric

Một biểu đồ phức tạp hơn

# A more complex plot with facets and multiple layers.
qplot(displ, hwy, data=mpg, facets = . ~ year) + geom_smooth()
## Error: ggplot2 doesn't know how to deal with data of class numeric

Các thành phần của ngữ pháp phân lớp

x <- 1:10
y <- factor(letters[1:5])
qplot(x, x, size = x)

plot of chunk scale

qplot(x, x, 1:10, colour = x)

plot of chunk scale

qplot(y, y, 1:10, shape = y)

plot of chunk scale

qplot(y, y, 1:10, colour = y)

plot of chunk scale

x1 <- c(1,10)
y1 <- c(1, 5)
p <- qplot(x1, y1, geom="blank", xlab=NULL, ylab=NULL) + theme_bw()
p

plot of chunk coord

p + coord_trans(y="log10")

plot of chunk coord

p + coord_polar()

plot of chunk coord

p <- qplot(displ, hwy, data = mpg, colour = factor(cyl))
## Error: ggplot2 doesn't know how to deal with data of class numeric
summary(p)
## data: [0x0]
## mapping: x = x1, y = y1
## faceting: facet_null()
## -----------------------------------
## geom_blank:
## stat_identity:
## position_identity: (width = NULL, height = NULL)
# Save plot object to disk
# save(p, file = "plot.rdata")
# Load from disk
# load("plot.rdata")
# Save png to disk
# ggsave("plot.png", width = 5, height = 5)