假设一个数据框
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)))
以及以下小提琴情节:
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())
不幸的是,当我收到消息时,这不起作用
Warning messages:
1: In transformation$transform(x) : NaNs produced
2: In scale_facet(expr = enquo(expr), "y", ..., type = type) :
log-10 transformation introduced infinite values.
3: In transformation$transform(x) : NaNs produced
4: In scale_facet(expr = enquo(expr), "y", ..., type = type) :
log-10 transformation introduced infinite values.
5: In transformation$transform(x) : NaNs produced
6: In scale_facet(expr = enquo(expr), "y", ..., type = type) :
log-10 transformation introduced infinite values.
7: In transformation$transform(x) : NaNs produced
8: In scale_facet(expr = enquo(expr), "y", ..., type = type) :
log-10 transformation introduced infinite values.
输入对数变换的值严格为正,因此这不是问题。我认为问题在于,仅在对数变换之后我才会获得负值(其指标是 y 轴的限制从 0 以上开始)。所以,我需要调整 y 轴,或者更准确地说,允许
breaks
取负值。如何做到这一点?
小提琴图在极值处扩展了数据,因此您可能会得到一些负值。您可以使用 pseudo_log 转换来防止警告:
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(),
trans = pseudo_log_trans(base = 10),
breaks = 10^(c(-5, -1, 0)),
labels = label_log())
请注意,如果您省略对
violin_plot
的调用,您将不会收到警告。