所有小提琴的面积与ggplot2中的小平面无关

时间:2017-11-08 08:29:42

标签: r ggplot2 data-visualization facet

我想创建一个三个不同因素的情节,其中所有小提琴都有相同的区域。但是使用facet_grid(. ~ C)似乎迫使每个方面内的小提琴(即只是因子C级别内的小提琴)具有相同的区域。我怎么能克服这个?

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)

enter image description here

2 个答案:

答案 0 :(得分:2)

首先,我们将创建一个具有预先计算密度的新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()

enter image description here

答案 1 :(得分:0)

Both of the below give the same plot as the faceted one:

ggplot(d, aes(x = paste(C,A), y = value, fill = B)) +
geom_violin(trim = FALSE, scale = "area") 

ggplot(d, aes(x =  C:A, y = value, fill = B)) +
geom_violin(trim = FALSE, scale = "area")

如果你能描述你的情节的目的,那将是很好的。正如其他方法可能更好地服务于您的目的,例如背对背密度或ggridges :: geom_density_ridges2:

ggplot(d,
aes(x = value, y = paste(A,B), fill = B, height = ..density..))+
ggridges::geom_density_ridges2(scale = 1.2,alpha=0.2,stat = "density")+
facet_grid(. ~ C)+
ggridges::theme_ridges()+
coord_flip()