当前位置:首页>java>半眼图绘制与R语言代码

半眼图绘制与R语言代码

  • 2026-10-14 14:31:29
半眼图绘制与R语言代码

在 R 语言里,「半眼图」通常指把「半小提琴(half-violin)+ 箱线(box)+ 散点(dot)」三张图拼成一张的「云雨图」。核心思路是:

  1. 用 ggdist 包的 stat_halfeye() 画左侧半小提琴;

  2. 用 ggplot2 的 geom_boxplot() 画中间箱线;

  3. 用 ggdist 的 stat_dots() 画右侧抖动散点。

下面给出可直接运行的完整示例(以 iris 数据为例):

# install.packages("ggdist")# install.packages("tidyquant")   # 仅为了配色,可选library(ggplot2)library(ggdist)# 1. 数据准备data <- irisdata$Species <- factor(data$Species,                       levels = c("virginica","versicolor","setosa"))# 2. 绘图p <-  ggplot(data,         aes(x = Species,             y = Sepal.Length,             fill = Species)) +  # 2.1 左侧半小提琴(半眼)  ggdist::stat_halfeye(    adjust = .5,          # 带宽    justification = -.2,  # 向左移    .width = 0,           # 不画区间横杠    point_colour = NA) +  # 不画中心点  # 2.2 中间箱线  geom_boxplot(    width = .12,    outlier.color = NA,   # 隐藏离群点    alpha = .5) +  # 2.3 右侧散点  ggdist::stat_dots(    side = "left",        # 点朝右    justification = 1.1,  # 向右移    binwidth = .03) +     # 点大小  # 3. 美化  scale_fill_manual(values = c("#FAC794","#F58F96","#AB97E0")) +  coord_flip() +              # 横过来更直观  theme_bw() +  theme(panel.grid = element_blank(),        legend.position = "none")print(p)
运行后即可得到一张典型的「半眼图」:左侧为半小提琴轮廓,中间为箱线,右侧为抖动散点,可一次性看出分布密度、集中趋势和原始数据位置 

最新文章

随机文章