1. 全部群架邊框
library(ggplot2)
library(shadowtext)
library(ggrepel)
library(ggunchull)
head(iris)
# 計算每個species的邊框
# setup a proper distance to extend (and simplify) the circle (here use 3% of the range of x axis)
delta_r <- 0.03
th_r <- 0.03
delta <- diff(range(iris$Sepal.Length)) * delta_r # 3% of the range of x axis
th <- diff(range(iris$Sepal.Width)) * th_r # 3% of the range of y axis
# 計算每個物種類型的中位數(shù)
species_type_med <- iris |>
dplyr::group_by(Species) |>
dplyr::summarise(
length_median = median(Sepal.Length), # x軸中位數(shù)
width_median = median(Sepal.Width) # y軸中位數(shù)
)
species_type_med
# 為數(shù)據(jù)添加微小的隨機擾動
iris_jittered <- iris
set.seed(123) # 設(shè)置隨機種子以確保結(jié)果可重現(xiàn)
iris_jittered$Sepal.Length <- iris_jittered$Sepal.Length + rnorm(nrow(iris_jittered), 0, 0.001)
iris_jittered$Sepal.Width <- iris_jittered$Sepal.Width + rnorm(nrow(iris_jittered), 0, 0.001)
# 使用添加擾動后的數(shù)據(jù)繪圖
ggplot(iris_jittered, aes(x = Sepal.Length, y = Sepal.Width, fill = Species)) +
geom_point(size = 3, shape = 21, color = "black") +
stat_unchull(
aes(color = Species, fill = Species), # 按Species著色和填充
alpha = 0.3, # 設(shè)置透明度為 0.3
delta = delta, # 使用計算的 x 軸擴展距離
th = th, # 使用計算的 y 軸擴展距離
n = 5 # 設(shè)置平滑度(控制邊界的圓滑程度)
) +
geom_shadowtext(
aes(x = length_median, y = width_median, label = Species),
fontface = "bold",
color = "black",
bg.colour='white',
data = species_type_med,
point.padding = unit(0.5, "lines")
) +
theme_classic() +
theme(
axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank()
)

image.png
2. 指定群架邊框
# 特定群加邊框
# 使用添加擾動后的數(shù)據(jù)繪圖
ggplot(iris_jittered, aes(x = Sepal.Length, y = Sepal.Width, fill = Species)) +
geom_point(size = 3, shape = 21, color = "black") +
stat_unchull(data = subset(iris_jittered, Species == "setosa"),
aes(color = Species, fill = Species), # 按Species著色和填充
alpha = 0.3, # 設(shè)置透明度為 0.3
delta = delta, # 使用計算的 x 軸擴展距離
th = th, # 使用計算的 y 軸擴展距離
n = 5 # 設(shè)置平滑度(控制邊界的圓滑程度)
) +
geom_shadowtext(
aes(x = length_median, y = width_median, label = Species),
fontface = "bold",
color = "black",
bg.colour='white',
data = species_type_med,
point.padding = unit(0.5, "lines")
) +
theme_classic() +
theme(
axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank()
)

image.png