You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot2带分位数小提琴图美学定制:线条样式与颜色设置问询

ggplot2小提琴图分位数样式与颜色调整方案

原始代码与需求

用户提供的小提琴图绘制代码如下:

library(ggplot2)
#Make data frame
Label <- c("Blue", "Blue", "Blue", "Blue","Red", "Red","Red","Red","Blue", "Blue","Blue","Blue")
n <- c(10, 223, 890, 34, 78, 902, 34, 211, 1007,209, 330, 446)
data <- data.frame(Label, n)

# make violin plot with quantiles
ggplot(data, aes(Label, n)) +
  geom_violin(legend = FALSE, trim = FALSE, adjust = 0.6, draw_quantiles = c(0.25, 0.5, 0.75)) 

当前所有分位数线条均为黑色,需求:

  • 将中位数(0.5分位数)线条加粗醒目,0.25/0.75分位数设为细虚线(或通过透明度区分)
  • 左侧小提琴填充色设为#42E894,右侧使用该颜色的浅色调,无需手动查找色值

1. 分位数线条样式调整

geom_violin的draw_quantiles无法直接为不同分位数设置差异化样式,可通过**两次调用geom_violin**实现:

  • 第一次绘制小提琴主体与0.25/0.75分位数,设置为细虚线
  • 第二次仅绘制中位数线条,设置为加粗实线(通过fill=NA避免覆盖原有小提琴)

示例代码:

library(ggplot2)
# 构建数据框
Label <- c("Blue", "Blue", "Blue", "Blue","Red", "Red","Red","Red","Blue", "Blue","Blue","Blue")
n <- c(10, 223, 890, 34, 78, 902, 34, 211, 1007,209, 330, 446)
data <- data.frame(Label, n)

ggplot(data, aes(Label, n)) +
  # 绘制小提琴主体+0.25/0.75分位数(细虚线)
  geom_violin(trim = FALSE, adjust = 0.6, 
              draw_quantiles = c(0.25, 0.75),
              linetype = "dashed", size = 0.5) +
  # 单独绘制中位数(加粗实线)
  geom_violin(trim = FALSE, adjust = 0.6, 
              draw_quantiles = 0.5,
              fill = NA, size = 1.2)

如果偏好透明度方案,可给0.25/0.75分位数添加alpha=0.5,中位数保持alpha=1,同样能突出中位数。


2. 小提琴颜色深浅调整

无需手动查找浅色调十六进制值,可使用scales包的lighten()函数直接调亮原颜色:

完整代码(结合样式调整)

library(ggplot2)
library(scales) # 加载颜色调整包

# 构建数据框
Label <- c("Blue", "Blue", "Blue", "Blue","Red", "Red","Red","Red","Blue", "Blue","Blue","Blue")
n <- c(10, 223, 890, 34, 78, 902, 34, 211, 1007,209, 330, 446)
data <- data.frame(Label, n)

ggplot(data, aes(Label, n, fill = Label)) +
  # 0.25/0.75分位数:细虚线
  geom_violin(trim = FALSE, adjust = 0.6, 
              draw_quantiles = c(0.25, 0.75),
              linetype = "dashed", size = 0.5) +
  # 中位数:加粗实线
  geom_violin(trim = FALSE, adjust = 0.6, 
              draw_quantiles = 0.5,
              fill = NA, size = 1.2) +
  # 设置填充色:左侧为#42E894,右侧调亮30%
  scale_fill_manual(values = c("Blue" = "#42E894", 
                               "Red" = lighten("#42E894", amount = 0.3))) +
  guides(fill = FALSE) # 隐藏填充色图例
  • lighten()的amount参数取值0-1,值越大颜色越浅;如需调暗可使用darken()函数
  • 若未安装scales包,先运行install.packages("scales")安装

内容的提问来源于stack exchange,提问作者MM1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:50:27