ggplot2: Position


Facet

Grid

library(ggplot2)
mpg2 <- subset(mpg, cyl != 5 & drv %in% c("4", "f"))
## Error in subset.default(mpg, cyl != 5 & drv %in% c("4", "f")): object 'cyl' not found
# Mặc định
qplot(cty, hwy, data = mpg2)
## Error in ggplot(data, aesthetics, environment = env): object 'mpg2' not found
# Thêm face grid 1 hàng nhiều cột:
qplot(cty, hwy, data = mpg2) + facet_grid(. ~ cyl)
## Error in ggplot(data, aesthetics, environment = env): object 'mpg2' not found
# Một cột nhiều hàng
qplot(cty, data = mpg2, geom="histogram", binwidth = 2) +
facet_grid(cyl ~ .)
## Error in ggplot(data, aesthetics, environment = env): object 'mpg2' not found
# Nhiều hàng nhiều cột
qplot(cty, hwy, data = mpg2) + facet_grid(drv ~ cyl)
## Error in ggplot(data, aesthetics, environment = env): object 'mpg2' not found

Đồ thị biên

p <- qplot(displ, hwy, data = mpg2) +
geom_smooth(method = "lm", se = F)
## Error in ggplot(data, aesthetics, environment = env): object 'mpg2' not found
p + facet_grid(cyl ~ drv) 
## Error in layout_base(data, rows, drop = drop): At least one layer must contain all variables used for facetting
# Biên
p + facet_grid(cyl ~ drv, margins = T)
## Error in layout_base(data, rows, drop = drop): At least one layer must contain all variables used for facetting
# Thêm màu cho đường smooth
qplot(displ, hwy, data = mpg2) +
geom_smooth(aes(colour = drv), method = "lm", se = F) +
facet_grid(cyl ~ drv, margins = T)
## Error in ggplot(data, aesthetics, environment = env): object 'mpg2' not found

Wrap

# Phân phối xếp hạng phim theo thập kỷ
library(plyr)
movies$decade <- round_any(movies$year, 10, floor)
qplot(rating, ..density.., data=subset(movies, decade > 1890),
geom="histogram", binwidth = 0.5) +
facet_wrap(~ decade, ncol = 6)

plot of chunk wrap

Scales

p <- qplot(cty, hwy, data = mpg)
## Error: ggplot2 doesn't know how to deal with data of class numeric
# scale cố định cho các facet
p + facet_wrap(~ cyl)
## Error in layout_base(data, vars, drop = drop): At least one layer must contain all variables used for facetting
# scale tự do cho mỗi facet
p + facet_wrap(~ cyl, scales = "free")
## Error in layout_base(data, vars, drop = drop): At least one layer must contain all variables used for facetting
# scale tự do đặc biệt hữu ích khi áp dụng với dữ liệu
# chuỗi thời gian với đo độ khác nhau
library(reshape2)
em <- melt(economics, id = "date")
qplot(date, value, data = em, geom = "line", group = variable) +
facet_grid(variable ~ ., scale = "free_y")

plot of chunk scale

mpg3 <- within(mpg2, {
model <- reorder(model, cty)
manufacturer <- reorder(manufacturer, -cty)
})
## Error in within(mpg2, {: object 'mpg2' not found
models <- qplot(cty, model, data = mpg3)
## Error in ggplot(data, aesthetics, environment = env): object 'mpg3' not found
models
## Error in eval(expr, envir, enclos): object 'models' not found
# scale tự do, space tự do
# opts() chuyển thành theme()
# theme_text() chuyển thành element_text()
models + facet_grid(manufacturer ~ ., scales = "free",
space = "free") + theme(strip.text.y = element_text())
## Error in eval(expr, envir, enclos): object 'models' not found

Group và Facet

xmaj <- c(0.3, 0.5, 1,3, 5)
xmin <- as.vector(outer(1:10, 10^c(-1, 0)))
ymaj <- c(500, 1000, 5000, 10000)
ymin <- as.vector(outer(1:10, 10^c(2,3,4)))
dplot <- ggplot(subset(diamonds, color %in% c("D","E","G","J")),
aes(carat, price, colour = color)) +
scale_x_log10(breaks = xmaj, labels = xmaj, minor = xmin) +
scale_y_log10(breaks = ymaj, labels = ymaj, minor = ymin) +
scale_colour_hue(limits = levels(diamonds$color)) +
theme(legend.position = "none")
# Group sẽ giống thế này
dplot + geom_point()

plot of chunk group vs facet

# Còn Facet thế này
dplot + geom_point() + facet_grid(. ~ color)

plot of chunk group vs facet

# Đường smooth
dplot + geom_smooth(method = lm, se = F, fullrange = T)

plot of chunk group vs facet

dplot + geom_smooth(method = lm, se = F, fullrange = T) + 
facet_grid(. ~ color)

plot of chunk group vs facet

Dodging và Faceting

# Dodge sẽ ra thế này
qplot(color, data=diamonds, geom = "bar", fill = cut,
position="dodge")

plot of chunk dodge vs. facet

# Còn Facet thế này
qplot(cut, data = diamonds, geom = "bar", fill = cut) +
facet_grid(. ~ color) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, size = 8,
colour = "grey50"))

plot of chunk dodge vs. facet

mpg4 <- subset(mpg, manufacturer %in% 
c("audi", "volkswagen", "jeep"))
## Error in match(x, table, nomatch = 0L): object 'manufacturer' not found
mpg4$manufacturer <- as.character(mpg4$manufacturer)
## Error in eval(expr, envir, enclos): object 'mpg4' not found
mpg4$model <- as.character(mpg4$model)
## Error in eval(expr, envir, enclos): object 'mpg4' not found
base <- ggplot(mpg4, aes(fill = model)) + 
geom_bar(position = "dodge") +
theme(legend.position = "none")
## Error in ggplot(mpg4, aes(fill = model)): object 'mpg4' not found
# dodge
base + aes(x = model)
## Error in eval(expr, envir, enclos): object 'base' not found
# face
base + aes(x = model) +
facet_grid(. ~ manufacturer)
## Error in eval(expr, envir, enclos): object 'base' not found
# scale phát  
last_plot() +
facet_grid(. ~ manufacturer, scales = "free_x", space = "free")
## Error in layout_base(data, cols, drop = drop): At least one layer must contain all variables used for facetting
base + aes(x = manufacturer)
## Error in eval(expr, envir, enclos): object 'base' not found

Biến liên tục

# Chia khoảng theo độ dài
mpg2$disp_ww <- cut_interval(mpg2$displ, length = 1)
## Error in cut(x, breaks(x, "width", n, length), include.lowest = TRUE, : object 'mpg2' not found
mpg2$disp_wn <- cut_interval(mpg2$displ, n = 6)
## Error in cut(x, breaks(x, "width", n, length), include.lowest = TRUE, : object 'mpg2' not found
# Chia khoảng theo số lượng điểm
mpg2$disp_nn <- cut_number(mpg2$displ, n = 6)
## Error in cut(x, breaks(x, "n", n), include.lowest = TRUE, ...): object 'mpg2' not found
plot <- qplot(cty, hwy, data = mpg2) + labs(x = NULL, y = NULL)
## Error in ggplot(data, aesthetics, environment = env): object 'mpg2' not found
plot + facet_wrap(~ disp_ww, nrow = 1)
## Error in layout_base(data, vars, drop = drop): At least one layer must contain all variables used for facetting
plot + facet_wrap(~ disp_wn, nrow = 1)
## Error in layout_base(data, vars, drop = drop): At least one layer must contain all variables used for facetting
plot + facet_wrap(~ disp_nn, nrow = 1)
## Error in layout_base(data, vars, drop = drop): At least one layer must contain all variables used for facetting

Hệ tọa độ

Các hệ tọa độ

Ví dụ ban đầu

rect <- data.frame(x = 50, y = 50)
line <- data.frame(x = c(1, 200), y = c(100, 1))
base <- ggplot(mapping = aes(x, y)) +
geom_tile(data = rect, aes(width = 50, height = 50)) +
geom_line(data = line)
# Mặc định Đề các
base

plot of chunk coord

# Tọa độ cực
base + coord_polar("x")

plot of chunk coord

base + coord_polar("y")

plot of chunk coord

# Đảo trục
base + coord_flip()

plot of chunk coord

# Biến đổi
base + coord_trans(y = "log10")

plot of chunk coord

# Đề-các cân bằng
base + coord_equal()

plot of chunk coord

Cách biến đổi hệ tọa độ

r_grid <- seq(0, 1, length = 15)
theta_grid <- seq(0, 3 / 2 * pi, length = 15)
extents <- data.frame(r = range(r_grid), theta = range(theta_grid))
base <- ggplot(extents, aes(r, theta)) + labs(aspect.ratio = 1) +
scale_y_continuous(expression(theta))
# Đường ban đầu
base + geom_point(colour = "red", size = 4) + geom_line()

plot of chunk trans2

pts <- data.frame(r = r_grid, theta = theta_grid)
# Chia đường thành các điểm
base + geom_line() + geom_point(data = pts)

plot of chunk trans2

base + geom_point(data = pts)

plot of chunk trans2

# Chuyển đổi điểm
xlab <- scale_x_continuous(expression(x == r * sin(theta)))
ylab <- scale_y_continuous(expression(x == r * cos(theta)))
polar <- base %+% pts + aes(x = r * sin(theta), y = r * cos(theta)) +
xlab + ylab
## Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.
polar + geom_point()

plot of chunk trans2

# Nối điểm thành đường
polar + geom_point() + geom_path()

plot of chunk trans2

# Kết quả
polar + geom_point(data=extents, colour = "red", size = 4) + geom_path()

plot of chunk trans2

Hệ tọa độ Đề-các

Đặt các giới hạn

(p <- qplot(disp, wt, data=mtcars) + geom_smooth())
## geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to change the smoothing method.

plot of chunk set limits

p + scale_x_continuous(limits = c(325, 500))
## geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to change the smoothing method.
## Warning: Removed 24 rows containing missing values (stat_smooth).
## Warning: Removed 24 rows containing missing values (geom_point).

plot of chunk set limits

p + coord_cartesian(xlim = c(325, 500))
## geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to change the smoothing method.

plot of chunk set limits

(d <- ggplot(diamonds, aes(carat, price)) + 
stat_bin2d(bins = 25, colour="grey70") +
theme(legend.position = "none"))

plot of chunk set limits

d + scale_x_continuous(limits = c(0, 2))

plot of chunk set limits

d + coord_cartesian(xlim = c(0, 2))

plot of chunk set limits

Đảo trục

qplot(displ, cty, data = mpg) + geom_smooth()
## Error: ggplot2 doesn't know how to deal with data of class numeric
qplot(cty, displ, data = mpg) + geom_smooth()
## Error: ggplot2 doesn't know how to deal with data of class numeric
qplot(cty, displ, data = mpg) + geom_smooth() + coord_flip()
## Error: ggplot2 doesn't know how to deal with data of class numeric

Biến đổi dữ liệu

qplot(carat, price, data = diamonds, log = "xy") + 
geom_smooth(method = "lm")

plot of chunk transform

library(scales)
last_plot() + coord_trans(x = exp_trans(10), y = exp_trans(10))

plot of chunk transform

Phi Đề-các

Tọa độ cực

(pie <- ggplot(mtcars, aes(x = factor(1), fill = factor(cyl))) +
geom_bar(width = 1))

plot of chunk polar

# Pie chart
pie + coord_polar(theta = "y")

plot of chunk polar

# The bullseye chart
pie + coord_polar()

plot of chunk polar

Tọa độ bản đồ

library(maps)
nz <- map_data("nz")
nzmap <- ggplot(nz, aes(x=long, y=lat, group=group)) +
geom_polygon(fill="white", colour="black")

# Tọa độ mặc định
nzmap

plot of chunk map

# Tọa độ bản đồ mặc định
nzmap + coord_map()

plot of chunk map

# Thông số khác
nzmap + coord_map("cylindrical")

plot of chunk map

nzmap + coord_map("azequalarea",orientation=c(-36.92,174.6,0))

plot of chunk map