【问题标题】:r - ggplot2 - split violin plot with more than 2 groupsr - ggplot2 - 超过 2 组的分割小提琴图
【发布时间】:2017-04-19 17:58:50
【问题描述】:

this thread 停止的地方继续。

我想在 ggplot 2 中制作一个分割小提琴图。上面介绍的方法仅限于 x 轴上的 2 个类别。

例子:

set.seed(20160229)
my_data = data.frame(
y=c(rnorm(1000), rnorm(1000, 0.5), rnorm(1000, 1), rnorm(1000, 1.5)),
x=c(rep('a', 2000), rep('b', 2000)),
m=c(rep('i', 1000), rep('j', 2000), rep('i', 1000)))

#Get densities
library(dplyr)
pdat <- my_data %>%
group_by(x, m) %>%
do(data.frame(loc = density(.$y)$x,
            dens = density(.$y)$y))

#Flip and offset densities for the groups
pdat$dens <- ifelse(pdat$m == 'i', pdat$dens * -1, pdat$dens)
pdat$dens <- ifelse(pdat$x == 'b', pdat$dens + 1, pdat$dens)
Plot

ggplot(pdat, aes(dens, loc, fill = m, group = interaction(m, x))) + 
geom_polygon() +
  scale_x_continuous(breaks = 0:1, labels = c('a', 'b')) +
  ylab('density') +
  theme_minimal() +
  theme(axis.title.x = element_blank())

看起来可以在 x 轴上放置 2 个以上的类别,但我不知道该怎么做。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我发现它是使用 for 循环按组因子级别定位形状的。

     set.seed(20160229)
    my_data = data.frame(
    y=c(rnorm(1000), rnorm(1000, 0.5), rnorm(1000, 1), rnorm(1000, 1.5), rnorm(1000, 1.25), rnorm(1000, 0.75)),
    x=c(rep('a', 2000), rep('b', 2000), rep('c', 2000)),
    m=c(rep('i', 1000), rep('j', 1000), rep('i', 1000,rep('j', 1000), rep('i', 1000,rep('j', 1000), rep('i', 1000)))
    
    #Get densities
    library(dplyr)
    pdat <- my_data %>%
    group_by(x, m) %>%
    do(data.frame(loc = density(.$y)$x,
                dens = density(.$y)$y))
    
    #Flip and offset densities for the groups
    pdat$dens <- ifelse(pdat$m == 'i', pdat$dens * -1, pdat$dens)
    
    #Flip and offset densities for x
        #for(pdat$x){pdat$dens <- (pdat$dens + (as.numeric(as.factor(pdat$x))))}
        for(i in 1:nrow(pdat)){(pdat$dens[i] <- (pdat$dens[i] + as.numeric(as.factor(pdat$x[i]))))}
    
    
        #Plot
        library(ggplot2)
        ggplot(pdat, aes(dens, loc, fill = m, group = interaction(m, x))) + 
          geom_polygon() +
          scale_x_continuous(breaks = (1:(as.numeric(length(levels(unique(pdat$x)))))), labels = levels(pdat$x)) +
    
          #scale_x_continuous(breaks = length(pdat$x), labels=pdat$x)+
          ylab("y") +
          theme_minimal() +
          theme(axis.title.x = element_blank())
    

    https://i.stack.imgur.com/bxfHh.png

    【讨论】:

    • 我认为不需要for 循环,只需pdat$dens &lt;- pdat$dens + as.numeric(as.factor(pdat$x)) 就可以了。
    猜你喜欢
    • 2016-06-13
    • 2018-01-15
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 2019-01-21
    • 2018-12-16
    相关资源
    最近更新 更多