--- layout: post title: "ggplot2: Grammar" published: yes --- ## Dữ liệu ```{r data} head(mpg) ``` ## Xây dựng biểu đồ điểm ```{r scatterplot} qplot(displ, hwy, data = mpg, colour = factor(cyl)) qplot(displ, hwy, data=mpg, colour=factor(cyl), geom="line") qplot(displ, hwy, data=mpg, colour=factor(cyl), geom="bar", stat="identity", position = "identity") # A complex plot without name qplot(displ, hwy, data=mpg, colour=factor(cyl)) + geom_smooth(data = subset(mpg, cyl != 5), method="lm") ``` ## Một biểu đồ phức tạp hơn ```{r complex} # A more complex plot with facets and multiple layers. qplot(displ, hwy, data=mpg, facets = . ~ year) + geom_smooth() ``` ## Các thành phần của ngữ pháp phân lớp ```{r scale} x <- 1:10 y <- factor(letters[1:5]) qplot(x, x, size = x) qplot(x, x, 1:10, colour = x) qplot(y, y, 1:10, shape = y) qplot(y, y, 1:10, colour = y) ``` ```{r coord} x1 <- c(1,10) y1 <- c(1, 5) p <- qplot(x1, y1, geom="blank", xlab=NULL, ylab=NULL) + theme_bw() p p + coord_trans(y="log10") p + coord_polar() ``` ```{r data structures} p <- qplot(displ, hwy, data = mpg, colour = factor(cyl)) summary(p) # 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) ```