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

R语言scale_y_facet绘制小提琴图:负对数轴值问题解决

解决log转换小提琴图的NaN/无限值警告问题

问题场景

假设存在如下数据框:

n <- 100
d <- data.frame("name" = c(rep("A", n), rep("B", n)),
                "type" = rep(c("X", "Y"), 2*n), 
                "value" = c(rnorm(n, 0, 1), rbeta(n, 1, 3)))

执行以下小提琴图绘制代码后,会出现多组NaN与无限值警告:

ggplot(d, aes(name, value, fill = type)) + 
  geom_violin(trim = F, position = dodge, na.rm = T) + 
  geom_boxplot(width = 0.1, position = dodge, na.rm = T) +
  facet_wrap(facets = ~name, scales = 'free') +
  theme(legend.position = "bottom",
        axis.title.x = element_blank(), 
        legend.title = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        legend.key.width = unit(0.5, "cm"))   +
  ggh4x::scale_y_facet(
    name == "B",
    trans  = "log10",
    breaks = breaks_log(),
    labels = label_log()) 

已知name == "B"的value均为严格正数,警告根源在于:beta(1,3)生成的是0-1之间的数值,log10转换后为负数,但breaks_log()默认会生成跨正负区间的刻度,这些正刻度对应原数据中不存在的>1数值,计算时就会产生无效值警告。

解决方案

方案1:手动指定对应原数据范围的刻度

直接定义log转换后的负刻度值,再转回原数值作为标签显示:

ggplot(d, aes(name, value, fill = type)) + 
  geom_violin(trim = F, position = position_dodge(width = 0.8), na.rm = T) + 
  geom_boxplot(width = 0.1, position = position_dodge(width = 0.8), na.rm = T) +
  facet_wrap(facets = ~name, scales = 'free') +
  theme(legend.position = "bottom",
        axis.title.x = element_blank(), 
        legend.title = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        legend.key.width = unit(0.5, "cm"))   +
  ggh4x::scale_y_facet(
    name == "B",
    trans  = "log10",
    # 指定对应原数据0.01-1范围的log转换刻度
    breaks = log10(c(0.01, 0.1, 1)),
    # 将log刻度转回原数值作为显示标签
    labels = function(x) 10^x
  )

方案2:限制breaks_log()的生成范围

通过limits参数约束刻度生成的原数据区间,避免无效刻度:

ggplot(d, aes(name, value, fill = type)) + 
  geom_violin(trim = F, position = position_dodge(width = 0.8), na.rm = T) + 
  geom_boxplot(width = 0.1, position = position_dodge(width = 0.8), na.rm = T) +
  facet_wrap(facets = ~name, scales = 'free') +
  theme(legend.position = "bottom",
        axis.title.x = element_blank(), 
        legend.title = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        legend.key.width = unit(0.5, "cm"))   +
  ggh4x::scale_y_facet(
    name == "B",
    trans  = "log10",
    # 限制刻度生成在原数据0.01-1的范围内
    breaks = breaks_log(limits = c(0.01, 1)),
    labels = label_log()
  )

额外优化

原代码中position = dodge建议改为position = position_dodge(width = 0.8),可以确保小提琴图与箱线图的分组对齐更准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 22:30:17