ggh4x軟件包是ggplot2擴(kuò)展軟件包胜嗓。它提供了一些不完全符合“圖形語法”概念的實(shí)用程序功能但在調(diào)整ggplots時(shí)仍然有用
下面通過幾個(gè)小例子來展示一下ggh4x的功能
devtools::install_github("teunbrand/ggh4x")
library(ggh4x)
library(tidyverse)
g <- ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
theme(axis.line = element_line(colour = "black"))
g
g + guides(x = "axis_truncated")
image.png
可以通過設(shè)置引導(dǎo)功能中的trunc_lower和trunc_upper來控制截?cái)噍S線的距離
g + guides(x = guide_axis_truncated(trunc_lower = unit(0.1, "npc"),
trunc_upper = unit(0.9, "npc")))
g + guides(x = guide_axis_truncated(trunc_lower = 2.5,
trunc_upper = 4.5))
在下面的示例中呐矾,使用interaction()函數(shù)將項(xiàng)目名稱及其所屬的組注釋在一起鳖悠。該guide_axis_nested()`以逗號將標(biāo)簽分開
df <- data.frame(
item = c("Coffee", "Tea", "Apple", "Pear", "Car"),
type = c("Drink", "Drink", "Fruit", "Fruit", ""),
amount = c(5, 1, 2, 3, 1))
df
> df
item type amount
1 Coffee Drink 5
2 Tea Drink 1
3 Apple Fruit 2
4 Pear Fruit 3
5 Car 1
ggplot(df, aes(interaction(item, type), amount)) +
geom_col() +
guides(x = "axis_nested")
可以使用paste0()功能將名稱與分組組合在一起挎袜。在以下情況下窘游,名稱會自動按字母順序排序况芒,可以使用delim參數(shù)來定義分割標(biāo)簽
ggplot(df, aes(paste0(item, "~nonsense~", type), amount)) +
geom_col() +
guides(x = guide_axis_nested(delim = "nonsense"))
ggplot(df, aes(weave_factors(item, type), amount)) +
geom_col() +
guides(x = "axis_nested")
ggh4x具有weave_factors()功能惜纸,該功保持輸入數(shù)據(jù)的自然順序
ggplot(df, aes(weave_factors(item, type), amount)) +
geom_col() +
guides(x = "axis_nested")
還可以修改刻度條顏色與注釋條信息
ggplot(df, aes(weave_factors(item, type), amount)) +
geom_col() +
guides(x = "axis_nested") +
theme(
axis.ticks = element_line(colour = "red"),
ggh4x.axis.nestline.x = element_line(size = 2),
ggh4x.axis.nesttext.x = element_text(colour = "blue"))
會可以堆砌注釋信息
df$type2 <- c(rep("Consumables", 4), "Vehicle")
df$appletea <- c("", rep("Ingredient of apple tea", 2), rep(NA, 2))
ggplot(df, aes(weave_factors(item, type, appletea, type2), amount)) +
geom_col() +
guides(x = "axis_nested")