ggplot2: Duplication


Dùng phép lặp last_plot()

library(ggplot2)
options(digits = 2)

# Dùng last_plot() để phóng to đoạn quan tâm
qplot(x, y, data = diamonds, na.rm = TRUE)

plot of chunk iteration

last_plot() + xlim(3, 11) + ylim(3, 11)

plot of chunk iteration

last_plot() + xlim(4, 10) + ylim(4, 10)
## Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
## Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.

plot of chunk iteration

last_plot() + xlim(4, 5) + ylim(4, 5)
## Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
## Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.

plot of chunk iteration

last_plot() + xlim(4, 4.5) + ylim(4, 4.5)
## Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
## Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.

plot of chunk iteration

last_plot() + geom_abline(colour = "red")

plot of chunk iteration

# Lệnh tổng hợp cuối cùng
qplot(x, y, data = diamonds, na.rm = T) +
geom_abline(colour = "red") +
xlim(4, 4.5) + ylim(4, 4.5)

plot of chunk iteration

Lưu mẫu biểu đồ

Lưu các đối tượng đơn

gradient_rb <- scale_colour_gradient(low = "red", high = "blue")
qplot(cty, hwy, data = mpg, colour = displ) + gradient_rb

plot of chunk single

qplot(bodywt, brainwt, data = msleep, colour = awake, log="xy") +
gradient_rb
## Warning: Removed 27 rows containing missing values (geom_point).

plot of chunk single

Lưu danh sách đối tượng

xquiet <- scale_x_continuous("", breaks = NULL)
yquiet <- scale_y_continuous("", breaks = NULL)
quiet <- list(xquiet, yquiet)

qplot(mpg, wt, data = mtcars) + quiet

plot of chunk list

qplot(displ, cty, data = mpg) + quiet

plot of chunk list

Dùng hàm đổi đối số mặc định của hàm

geom_lm <- function(formula = y ~ x) {
geom_smooth(formula = formula, se = FALSE, method = "lm")
}
qplot(mpg, wt, data = mtcars) + geom_lm()

plot of chunk func

library(splines)
qplot(mpg, wt, data = mtcars) + geom_lm(y ~ ns(x, 3))

plot of chunk func

Lưu hàm biểu đồ

pcp_data <- function(df) {
libs <- c("plyr","reshape2")
lapply(libs, require, character.only = TRUE)
numeric <- laply(df, is.numeric)
# Rescale numeric columns
range01 <- function(x) x / range(x)
df[numeric] <- colwise(range01)(df[numeric])
# Add row identified
df$.row <- rownames(df)
# Melt, using non-numeric variables as id vars
dfm <- melt(df, id = c(".row", names(df)[!numeric]))
# Add pcp to class of the data frame
class(dfm) <- c("pcp", class(dfm))
dfm
}
pcp <- function(df, ...) {
df <- pcp_data(df)
ggplot(df, aes(variable, value)) + geom_line(aes(group = .row))
}
pcp(mpg)

plot of chunk plot functions

pcp(mpg) + aes(colour = drv)

plot of chunk plot functions