今天介绍一个实用的作图R包{ggh4x},让{ggplot2}更加强大~
下面将从facet函数、guides函数,以及scale函数等几个方面介绍。
安装并载入R包:
install.packages("ggh4x")
library(ggh4x)
创建作图数据:
set.seed(1)
df <- data.frame(
category = rep(c("A", "B", "C"), each = 20),
group = rep(c("G1", "G2"), 30),
test = rep(c("t1", "t2", "t3", "t4", "t5"), 12),
value = rnorm(30, 10, 2),
value2 = rnorm(30, 5, 2)
)
summary(df)
p1 <- ggplot(df, aes(x = category, y = value, fill = group)) +
geom_col(position = "dodge") +
labs(x = "Categories", y = "Values", fill = "Groups") +
theme_light()
p1
p1 + facet_wrap2(~test)
p1 + facet_wrap2(~test,
axes = "all", # 展示所有亚图上x和y轴的刻度文字和刻度点
remove_labels = "x") # 去除重叠部分x轴上刻度文字
p1 + facet_grid2(group ~ test,
axes = "all", # 包含:x, y, all
scales = "free") # 包含:fixed(默认), free_x, free_y, free
p1 + facet_nested(~ group + category,
scales = "free")
p1 + facet_nested(~ group + category,
scales = "free",
switch = "x") +
theme(ggh4x.facet.nestline = element_line(colour = "gold3"))
my_style <- matrix(c(1,2,3,4, 5, 5), 2, 3) # 自定义亚图片排列布局
p1 + facet_manual(~ test, my_style)
p2 <- ggplot(df, aes(x = value, y = value2, color = group)) +
geom_point(show.legend = F) +
theme_classic()
p2
p2 + guides(x = guide_axis_truncated(trunc_lower = 8, trunc_upper = 12))
p2 + scale_y_continuous(guide = "axis_minor",
minor_breaks = seq(6, 8, by = 0.2))
p2 + scale_y_continuous(guide = "axis_minor",
minor_breaks = seq(6, 8, by = 0.2)) +
theme(axis.ticks.length = unit(2, "mm"),
ggh4x.axis.ticks.length.minor = rel(1)) # 调整大刻度和小刻度的比例
[1]. https://github.com/teunbrand/ggh4x