我想为三个不同的因素创建一个图,其中所有 fiddle 的面积都相同。但是使用facet_grid(. ~ C)
似乎会迫使每个小平面内的 fiddle (即仅在因子C级别内的 fiddle )具有相同的面积。我该如何克服呢?
library(ggplot2)
d <- data.frame(value = c(906, 1013, 1109, 876, 747, 759, 876, 1358, 739,
1086, 807, 954, 1586, 762, 1353, 1221, 976, 1002,
1129, 943, 1270, 1126, 853, 950, 677, 696, 681,
615, 736, 595, 590, 618, 524, 1014, 515, 645, 860,
874, 934, 728, 1078, 659, 1024, 786, 821, 541,
681, 744),
A = gl(2, 12, 48),
B = gl(2, 6, 48),
C = gl(2, 24))
ggplot(d, aes(x = A, y = value, fill = B)) +
geom_violin(trim = FALSE, scale = "area") +
facet_grid(. ~ C)
最佳答案
首先,我们将创建一个具有预先计算的密度的新data.frame
:
library('tidyverse')
d2 <- d %>%
group_by(A, B, C) %>%
do({
dens <- density(.$value)
tibble(x = c(head(dens$x, 1), dens$x, tail(dens$x, 1)), #Add 0s at end to close lines
y = c(0, dens$y, 0))
}) %>%
ungroup() %>%
mutate(ymin = as.numeric(A:B) - .4*y/max(y), # Add offset for factor levels
ymax = as.numeric(A:B) + .4*y/max(y))
现在,我们将密度绘制为色带:
ggplot(d2)+
aes(x = x,
ymin = ymin,
ymax = ymax,
group = A:B,
fill = B)+
geom_ribbon()+
# Enclosing lines
geom_line(aes(y = ymin))+
geom_line(aes(y = ymax))+
facet_grid(. ~ C)+
scale_y_continuous(breaks = c(1.5, 2.5),
minor_breaks = c(1.5, 3.5),
labels = levels(d2$A))+
labs(x = 'value', y = 'A')+
coord_flip()
关于r - 所有 fiddle 的面积均相同,与ggplot2中的构面无关,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47174825/