2025-01-21 ggplot2文字加背景,群加邊框

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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容