You are on page 1of 2

Trực quan hóa số liệu Geoms - Sử dụng geom để biểu diễn các điểm dữ liệu, sử dụng các thuộc

om để biểu diễn các điểm dữ liệu, sử dụng các thuộc tính của aes để biểu diễn các biến. Mỗi hàm sẽ tạo ra một lớp
với ggplot2
Các thuộc tính hình học cơ bản Biểu đồ hai biến
Cheat Sheet a <- ggplot(seals, aes(x = long, y = lat)) Biến X liên tục, biến Y liên tục Hai biến phân phối liên tục
e <- ggplot(mpg, aes(cty, hwy)) h <- ggplot(diamonds, aes(carat, price))
b <- ggplot(economics, aes(date, unemploy))
e + geom_label(aes(label = cty), nudge_x = 1, h + geom_bin2d(binwidth = c(0.25, 500))
a + geom_blank() A C nudge_y = 1, check_overlap = TRUE) x, y, alpha, color, fill, linetype, size, weight
B x, y, label, alpha, angle, color, family, fontface,
Kiến thức cơ bản a + geom_curve(aes(yend = lat + delta_lat,
hjust, lineheight, size, vjust
h + geom_density2d()
ggplot2 dựa trên khái niệm “ngữ pháp của e + geom_jitter(height = 2, width = 2) x, y, alpha, colour, group, linetype, size
xend = long + delta_long, curvature = z)) x, y, alpha, color, fill, shape, size
biểu đồ”, trong đó tất cả các biểu đồ đều có thể x, xend, y, yend, alpha, angle, color, curvature,
được xây dựng từ những thành phần giống linetype, size
e + geom_point() h + geom_hex()
nhau: data - tập dữ liệu, geoms – mô tả cách x, y, alpha, color, fill, shape, size, stroke
b + geom_path(lineend="butt", x, y, alpha, colour, fill, size
thức thể hiện dữ liệu, và coordinate - một hệ
linejoin="round’, linemitre=1)
tọa độ.
x, y, alpha, color, group, linetype, size e + geom_quantile() Hàm liên tục
x, y, alpha, color, group, linetype, size, weight i <- ggplot(economics, aes(date, unemploy))
b + geom_polygon(aes(group = group))
x, y, alpha, color, fill, group, linetype, size
i + geom_area()
e + geom_rug(sides = "bl") x, y, alpha, color, fill, linetype, size
x, y, alpha, color, linetype, size
a + geom_rect(aes(xmin = long, ymin = lat,
Để hiển thị các điểm dữ liệu, cần phải sắp xếp xmax= long + delta_long, ymax = lat + delta_lat)) i + geom_line()
các biến trong dữ liệu với các thuộc tính hình e + geom_smooth(method = lm) x, y, alpha, color, group, linetype, size
xmax, xmin, ymax, ymin, alpha, color, fill, linetype, x, y, alpha, color, fill, group, linetype, size,
học (geom) như kích cỡ, màu sắc, trục tọa độ x size weight
& y
i + geom_step(direction = "hv")
C e + geom_text(aes(label = cty), nudge_x = 1,
b + geom_ribbon(aes(ymin=unemploy - 900, nudge_y = 1, check_overlap = TRUE) x, y, alpha, color, group, linetype, size
ymax=unemploy + 900)) A x, y, label, alpha, angle, color, family, fontface,
x, ymax, ymin, alpha, color, fill, group, linetype, B hjust, lineheight, size, vjust
size Trực quan hóa sai số
df <- data.frame(grp = c("A", "B"), fit = 4:5, se = 1:2)
j <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se))
a + geom_segment(aes(yend=lat + delta_lat, Biến X rời rạc, biến Y liên tục
xend = long + delta_long)) f <- ggplot(mpg, aes(class, hwy))
Vẽ biểu đồ với ggplot() hoặc qplot() x, xend, y, yend, alpha, color, linetype, size j + geom_crossbar(fatten = 2)
f + geom_bar(stat = "identity") x, y, ymax, ymin, alpha, color, fill, group,
Sắp xếp thuộc tính aes Dữ liệu
linetype, size
geom
a + geom_spoke(aes(yend = lat + delta_lat, x, y, alpha, color, fill, linetype, size, weight
qplot(x = cty, y = hwy, color = cyl, data = mpg, geom = "point") xend = Biểu đồ một biến
long + delta_long))
x, y, angle, radius, alpha, color, linetype, size f + geom_boxplot() j + geom_errorbar()
Tạo một biểu đồ hoàn chỉnh với dữ liệu, geom & thuộc
tính cho trước. Hỗ trợ nhiều chế độ mặc định
Biến liên tục x, y, lower, middle, upper, ymax, ymin, alpha, x, ymax, ymin, alpha, color, group, linetype,
color, fill, group, linetype, shape, size, weight size, width (also geom_errorbarh())
c <- ggplot(mpg, aes(hwy))
j + geom_linerange()
ggplot(data = mpg, aes(x = cty, y = hwy)) c + geom_area(stat = "bin") x, ymin, ymax, alpha, color, group, linetype,
f + geom_dotplot(binaxis = "y",
Thêm các lớp (layer) vào biểu đồ đã tạo, hỗ trợ x, y, alpha, color, fill, linetype, sizec + stackdir = "center") size
nhiều loại biểu đồ hơn qplot(). geom_area(aes(y = ..density..), stat = "bin") x, y, alpha, color, fill, group j + geom_pointrange()
x, y, ymin, ymax, alpha, color, fill, group,
Dữ liệu Thêm các lớp với c + geom_density(kernel = "gaussian") f + geom_violin(scale = "area") linetype, shape, size
dấu + x, y, alpha, color, fill, group, linetype, size, weight
ggplot(mpg, aes(hwy, cty)) + x, y, alpha, color, fill, group, linetype, size,
geom_point(aes(color = cyl)) + Lớp (layer) = weight Bản đồ
geom_smooth(method ="lm") + geom + default c + geom_dotplot() data <- data.frame(murder = USArrests$Murder,
coord_cartesian() + stat + các thuộc state = tolower(rownames(USArrests)))
tính khác x, y, alpha, color, fill Biến X rời rạc, biến Y rời rạc
scale_color_gradient() + map <- map_data("state")
theme_bw() g <- ggplot(diamonds, aes(cut, color)) k <- ggplot(data, aes(fill = murder))
Các thành phần c + geom_freqpoly()
khác k + geom_map(aes(map_id = state), map = map) +
x, y, alpha, color, group, linetype, size g + geom_count()
expand_limits(x = map$long, y = map$lat)
Thêm lớp mới trong biểu đò với hàm geom_*() x, y, alpha, color, fill, shape, size, stroke map_id, alpha, color, fill, linetype, size
hoặc stat_*(). Mỗi hàm sẽ xác định một
"geom", là một nhóm các thuộc tính hình học, c + geom_histogram(binwidth = 5)
các tính toán mặc đinh và sự sắp xếp vị trí
x, y, alpha, color, fill, linetype, size, weight
Biểu đồ ba biến
trong biểu đồ. l + geom_raster(aes(fill = z), hjust=0.5,
last_plot() a + geom_histogram(aes(y = ..density..)) seals$z <- with(seals, sqrt(delta_long^2 + delta_lat^2))
Biến rời rạc vjust=0.5, interpolate=FALSE)
Trả về biểu đồ đã tạo gần nhất l <- ggplot(seals, aes(long, lat)) x, y, alpha, fill
d <- ggplot(mpg, aes(fl))
ggsave("plot.png", width = 5, height = 5) l + geom_contour(aes(z = z)) l + geom_tile(aes(fill = z))
d + geom_bar() x, y, z, alpha, colour, group, linetype, size, x, y, alpha, color, fill, linetype, size, width
Lưu biểu đồ đã tạo gần nhất với kích thước 5’ x
x, alpha, color, fill, linetype, size, weight weight
5’, lưu với tên “plot.png” tại thư mục làm việc

RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • info@rstudio.com • 844-448-1212 • rstudio.com Translator: ranalytics.vn Xem thêm: docs.ggplot2.org • ggplot2 2.0.0 • Updated: 12/15
Stats – cách thức khác để tạo biểu đồ Scales – Tỷ lệ Coordinate – Hệ tọa độ Faceting – Chia nhỏ biểu đồ
Một số biểu đồ hiển thị dữ liệu đã được biến đổi. Sử Scales – Tỷ lệ quy định cách thức biểu đồ sắp xếp r <- d + geom_bar() Chia nhỏ biểu đồ dựa trên giá trị của một hoặc
dụng stat để lựa chọn hình thức biến đổi dữ liệu, VD. dữ liệu với các thuộc tính hình học trên biểu đồ. Để nhiều biến rời rạc
r + coord_cartesian(xlim = c(0, 5)) t <- ggplot(mpg, aes(cty, hwy)) + geom_point()
a + geom_bar(stat = "count") thay đổi cách sắp xếp này, cần thay đổi tỷ lệ. xlim, ylim
n <- b + geom_bar(aes(fill = fl)) Hệ tọa độ Đề-các mặc định t + facet_grid(. ~ fl)
n Cột chứa biến fl
r + coord_fixed(ratio = 1/2)
aes cần Sắp xếp tỷ lệ Các giá trị ratio, xlim, ylim
scale_ t + facet_grid(year ~ .)
thay đổi để sử dụng thuộc tính
Hệ tọa độ Đề-các, tỷ lệ x và y cố định Hàng chưa biến year
Mỗi stat sẽ tạo thêm các biến mới ứng với các n + scale_fill_manual(
values = c("skyblue", "royalblue", "blue", "navy"), t + facet_grid(year ~ fl)
các thuộc tính hình hình học Các biến này sử limits = c("d", "e", "p", "r"), breaks =c("d", "e", r + coord_flip()
Chia nhỏ biểu đồ theo cả hàng và cột
dụng cấu trúc thông thường ..name.. "p", "r"), xlim, ylim
Hàm stat và geom đều kết hợp một stat với một name = "fuel", labels = c("D", "E", "P", "R")) Đổi trục tọa độ t + facet_wrap(~ fl)
Tự động sắp xếp biểu đồ
geom để tạo một lớp (layer) mới, VD. Khoảng giá trị cho Tên sử dụng Nhãn sử dụng Các giá trị được Quy định tỷ lệ để giới hạn các trục của biểu đồ
stat_count(geom="bar") cho ra kết quả tương tự sắp xếp lại tỷ lệ cho chú giải cho chú giải dùng cho chú giải r + coord_polar(theta = "x", khi sử dụng facet
direction=1 )
như geom_bar(stat="count") Biến mới tạo qua t + facet_grid(drv ~ fl, scales = "free")
theta, start, direction
Hàm stat aes biến đổi dữ liệu Cách sử dụng thường dùng Hệ tọa độ cực Giới hạn trục x & y theo từng biểu đồ
Sử dụng với các giá trị aes:
i + stat_density2d(aes(fill = ..level..), • "free_x" – Tự động điều chỉnh giới hạn trục x
alpha, color, fill, linetype, shape, size
geom = "polygon", n = 100) r + coord_trans(ytrans = "sqrt") • "free_y" – Tự động điều chỉnh giới hạn trục y
scale_*_continuous() – Sử dụng cho các biến liên tục xtrans, ytrans, limx, limy
geom Tham số scale_*_discrete() – Sử dụng cho các biến rời rạc Biến đổi hệ tọa độ Đề-các,
c + stat_bin(binwidth = 1, origin = 10) scale_*_identity() – Sử dụng giá trị của tập dữ liệu Đặt nhãn, tiêu đồ cho các biểu đồ khi dùng facet
x, y | ..count.., ..ncount.., ..density.., ..ndensity.. Biểu đồ scale_*_manual(values = c()) – Sắp xếp các biến rời t + facet_grid(. ~ fl, labeller = label_both)
một biến rạc với các giá trị tùy biến
c + stat_count(width = 1) π + coord_map(projection = "ortho", fl: c fl: d fl: e fl: p fl: r
x, y, | ..count.., ..prop.. orientation=c(41, -74, 0))
c + stat_density(adjust = 1, kernel = "gaussian") t + facet_grid(fl ~ ., labeller = label_bquote(alpha ^ .(fl)))
projection, orientation, xlim, ylim
x, y, | ..count.., ..density.., ..scaled.. X and Y location scales
Sử dụng với các thuộc tính của trục x hoặc y
e + stat_bin_2d(bins = 30, drop = TRUE) Biểu đồ Sử dụng packages mapproj (mercator (mặc định), t + facet_grid(. ~ fl, labeller = label_parsed)
x, y, fill | ..count.., ..density..
(phần dưới đây chỉ mô tả trục hoành x) azequalarea, lagrange,...) c d e p r
hai biến
e + stat_bin_hex(bins = 30)
scale_x_date(date_labels = "%m/%d"),
x, y, fill | ..count.., ..density..
e + stat_density_2d(contour = TRUE, n = 100)
date_breaks = "2 weeks") - Coi x như biến ngày Điều chỉnh vị trí Labels – Tiêu đề & nhãn
tháng. Xem thêm ?strptime về nhãn (label)
x, y, color, size | ..level.. Cách thức sắp xếp các thuộc tính hình học t + ggtitle("New Plot Title")
e + stat_ellipse(level = 0.95, segments = 51, type = "t") scale_x_datetime() - Coi x như biến ngày tháng, sử Thêm tên biểu đồ
dụng các tham số như scale_x_date() (geom) trên biểu đồ
t + xlab("New X label") Sử dụng các hàm tỷ
l + stat_contour(aes(z = z)) Biểu đồ scale_x_log10() – Thê hiện x với tỷ lệ log10 s <- ggplot(mpg, aes(fl, fill = drv)) lệ (scale) để thay đổi,
Thay đổi tên trục x cập nhật các chú giải
x, y, z, order | ..level.. ba biến scale_x_reverse() – Giữ nguyên hướng của trục x s + geom_bar(position = "dodge")
l + stat_summary_hex(aes(z = z), bins = 30, fun = mean) t + ylab("New Y label")
scale_x_sqrt() – Thể hiện x với tỷ lệ căn bậc hai Đặt các giá trị cạnh nhau
x, y, z, fill | ..value.. Thay đổi tên trục y
l + stat_summary_2d(aes(z = z), bins = 30, fun = mean) Màu sắc s + geom_bar(position = "fill")
t + labs(title =" New title", x = "New x",
x, y, z, fill | ..value.. Biến rời rạc Biến liên tục Đặt các giá trị chồng lên nhau, thay đổi tỷ
lệ theo phần trăm y = "New y")
f + stat_boxplot(coef = 1.5) So sánh n <- d + geom_bar( o <- c + geom_dotplot( e + geom_point(position = "jitter") Thay đổi tên biểu đồ và các trục x, y
x, y | ..lower.., ..middle.., ..upper.., ..width.. , ..ymin.., ..ymax.. aes(fill = fl)) aes(fill = ..x..))
f + stat_ydensity(adjust = 1, kernel = "gaussian", scale = "area") Thêm các yếu tố ngẫu nhiên (random
x, y | ..density.., ..scaled.., ..count.., ..n.., ..violinwidth.., ..width..
n + scale_fill_brewer( o + scale_fill_gradient( noise) để tránh chống lấn các điểm trên Chú giải
palette = "Blues") low = "red", biểu đồ
Lựa chọn bảng màu: high = "yellow") A n + theme(legend.position = "bottom")
e + stat_ecdf(n = 40) o + scale_fill_gradient2( e + geom_label(position = "nudge")
Hàm số library(RColorBrewer)
low = "red", high = "blue",
B
Đặt các nhãn bên cạnh các điểm Thay đổi vị trí chú giải: ”up”,“bottom”, “right”,”left”
x, y | ..x.., ..y.. display.brewer.all()
e + stat_quantile(quantiles = c(0.25, 0.5, 0.75), formula = y mid = "white", midpoint = 25) s + geom_bar(position = "stack") n + guides(fill = "none")
n + scale_fill_grey( o + scale_fill_gradientn(
~ log(x), start = 0.2, end = 0.8, colours = terrain.colors(6) ) Đặt các giá trị chồng lên nhau Quy đinh chú giải cho mỗi thuộc tính: colorbar,
method = "rq") na.value = "red") Xem thêm: rainbow(), legend, hoặc “none" (không để chú giải)
x, y | ..quantile.. heat.colors(), topo.colors(), n + scale_fill_discrete(name = "Title",
e + stat_smooth(method = "auto", formula = y ~ x, se = cm.colors(), Vị trí trong biểu đồ có thể được thay đổi lại thành một
TRUE, n = 80, RColorBrewer::brewer.pal() hàm với các tham số của chiều dài và chiều rộng labels = c("A", "B", "C", "D", "E"))
fullrange = FALSE, level = 0.95) Hình dạng s + geom_bar(position = position_dodge(width = 1)) Sử dụng hàm tỷ lệ (scale) cho tiêu đề & nhãn trong
x, y | ..se.., ..x.., ..y.., ..ymin.., ..ymax..
Giá trị thuộc tính hình dạng chú giải
ggplot() + stat_function(aes(x = -3:3),
Cách dùng p <- e + geom_point(
fun = dnorm, n = 101, args = list(sd=0.5))
x | ..x.., ..y.. thông dụng
aes(shape = fl, size = cyl)) Themes – Hình nền trong biểu đồ Zooming – Phóng tó biểu đồ
e + stat_identity(na.rm = TRUE)
p + scale_shape(
r + theme_classic() Không thay đổi dữ liệu (Nên dùng)
solid = FALSE) r + theme_bw()
ggplot() + stat_qq(aes(sample=1:100), distribution = qt, Nền trắng Nền classic t + coord_cartesian(
dparams = list(df=5)) p + scale_shape_manual( xlim = c(0, 100), ylim = c(10, 20))
sample, x, y | ..sample.., ..theoretical.. values = c(3:7))
r + theme_gray() r + theme_minimal()
e + stat_sum()
Gía trị thuộc tính hình dạng
trong bảng bên Nền xám (theme
Thay đổi dữ liệu
Nền minimal
x, y, size | ..n.., ..prop.. mặc định) (Loại bỏ các dữ liệu ngoài vùng phân tích)
e + stat_summary(fun.data = "mean_cl_boot") Kích cỡ r + theme_dark() r + theme_void() t + xlim(0, 100) + ylim(10, 20)
h + stat_summary_bin(fun.y = "mean", geom = "bar") p + scale_radius( p + scale_size_area( Nền tối t + scale_x_continuous(limits = c(0, 100))
e + stat_unique() max_scale = 6)
Để trống hình nền
range=c(1,6)) + scale_y_continuous(limits = c(0, 100))
p + scale_size() Kích cỡ dạng tròn

RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • info@rstudio.com • 844-448-1212 • rstudio.com Translator: ranalytics.vn Xem thêm: docs.ggplot2.org • ggplot2 2.0.0 • Updated: 12/15

You might also like