本文在 http://www.cookbook-r.com/Graphs/Facets_(ggplot2)/的基础上加入了自己的理解
ggplot2的数据分面就是根据数据中的不同分组,绘制多个图形.
数据预览
library(reshape2)
head(tips)
## total_bill tip sex smoker day time size
## 1 16.99 1.01 Female No Sun Dinner 2
## 2 10.34 1.66 Male No Sun Dinner 3
## 3 21.01 3.50 Male No Sun Dinner 3
## 4 23.68 3.31 Male No Sun Dinner 2
## 5 24.59 3.61 Female No Sun Dinner 4
## 6 25.29 4.71 Male No Sun Dinner 4
绘制散点图
library(ggplot2)
sp <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1)
sp
facet_grid
facet_grid()
可以根据数据的不同分组, 将图形按照 水平或者垂直方向 进行分割.共享x轴或者轴.
# 垂直方向进行分割
sp + facet_grid(sex ~ .)
# 水平方向分割
sp + facet_grid(. ~ sex)
# 对 sex 进行垂直分割, 对 day 进行水平分割
sp + facet_grid(sex ~ day)
facet_wrap
facet_wrap()
可以根据行列的数值进行分割
# 水平分割, 分为两列
sp + facet_wrap( ~ day, ncol=2)
修改分页的标签外观
sp + facet_grid(sex ~ day) +
theme(strip.text.x = element_text(size=8, angle=75),
strip.text.y = element_text(size=12, face="bold"),
strip.background = element_rect(colour="red", fill="#CCCCFF"))
修改分页标签文字
labels <- c(Female = "Women", Male = "Men")
sp + facet_grid(. ~ sex, labeller=labeller(sex = labels))
或者直接进行赋值
tips2 <- tips
levels(tips2$sex)[levels(tips2$sex)=="Female"] <- "Women"
levels(tips2$sex)[levels(tips2$sex)=="Male"] <- "Men"
head(tips2, 3)
## total_bill tip sex smoker day time size
## 1 16.99 1.01 Women No Sun Dinner 2
## 2 10.34 1.66 Men No Sun Dinner 3
## 3 21.01 3.50 Men No Sun Dinner 3
# Both of these will give the same output:
sp2 <- ggplot(tips2, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1)
sp2 + facet_grid(. ~ sex)
labeller
labeller()
通过输入一个方法
, 对字符串进行该方法
处理的,重新返回字符串.
# Reverse each strings in a character vector
reverse <- function(strings) {
strings <- strsplit(strings, "")
vapply(strings, function(x) {
paste(rev(x), collapse = "")
}, FUN.VALUE = character(1))
}
sp + facet_grid(. ~ sex, labeller=labeller(sex = reverse))
设置范围
一般情况下, 坐标轴的范围是固定的,也就是每幅图都有相同的尺寸和范围, 当然也可以设置free
, free_x
, 或者 free_y
自由改变坐标轴的范围.
hp <- ggplot(tips, aes(x=total_bill)) + geom_histogram(binwidth=2,colour="white")
# Histogram of total_bill, divided by sex and smoker
hp + facet_grid(sex ~ smoker)
# scales="free_y", y轴自由设置
hp + facet_grid(sex ~ smoker, scales="free_y")
# With panels that have the same scaling, but different range (and therefore different physical sizes)
hp + facet_grid(sex ~ smoker, scales="free", space="free")
时间: 2024-11-05 17:28:47