与ggplot2中的面无关的所有小提琴的相同区域 [英] same area for all violins independent of facets in ggplot2

查看:25
本文介绍了与ggplot2中的面无关的所有小提琴的相同区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为三个不同的因素创建一个曲线图,其中所有小提琴都有相同的面积。但使用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)

推荐答案

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

这篇关于与ggplot2中的面无关的所有小提琴的相同区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆