简体   繁体   English

R中的分组箱线图

[英]Grouped boxplot in R

df <- data.frame(values = c(2.5,12,4.8,56,78),samples = c('45fe.K2','59ji.K2','59rc.K1','45hi.K1','96hu.K1'),group = c('K2','K2','K1','K1','K1'))

 df
  values samples group
1    2.5 45fe.K2    K2
2   12.0 59ji.K2    K2
3    4.8 59rc.K1    K1
4   56.0 45hi.K1    K1
5   78.0 96hu.K1    K1

I want to generate a group grouped boxplot.我想生成一个group分组箱线图。 So I want one plot with a K1 and K2 boxplot.所以我想要一个带有K1K2箱线图的图。 I thought this https://www.r-graph-gallery.com/265-grouped-boxplot-with-ggplot2.html would do it but I can´t figure out how我认为这个https://www.r-graph-gallery.com/265-grouped-boxplot-with-ggplot2.html可以做到,但我不知道如何

p1 <- ggplot(df, aes(x=group, y=values, fill=group)) + 
    geom_boxplot() +
    facet_wrap(~group)

What can I do about that?我能做些什么呢? I tried also x=samples but that is wrong.我也试过x=samples但那是错误的。

EDIT: Maybe that is another question.编辑:也许这是另一个问题。 But when I add the group column with the following code the great answer by @rodolfoksveiga results in an error但是,当我使用以下代码添加group列时,@rodolfoksveiga 的出色回答会导致错误

df <- data.frame(values = c(2.5, 12, 4.8, 56, 78),
samples = c('45fe.K2', '59ji.K2', '59rc.K1', '45hi.K1', '96hu.K1'))

df$group <- NA
df$group <- apply(df,1,function(x)
{ifelse(grepl('K2',df$samples) == TRUE,paste('K2'),paste('K1'))})

Error in `$<-.data.frame`(`*tmp*`, "PANEL", value = c(1L, 2L, 2L, 2L,  : 
 replacement has ... rows, data has ....rows

Welcome to Stack Overflow Joris.欢迎来到 Stack Overflow Joris。

Maybe this is what you want:也许这就是你想要的:

library(ggplot2)
df <- data.frame(values = c(2.5, 12, 4.8, 56, 78),
                 samples = c('45fe.K2', '59ji.K2', '59rc.K1', '45hi.K1', '96hu.K1'),
                 group = c('K2', 'K2', 'K1', 'K1', 'K1'))
ggplot(df, aes(x = group, y = values, fill = group)) + 
  geom_boxplot() +
  facet_wrap(. ~ group, scales = 'free_x')

Here is the output:这是输出:

在此处输入图片说明

Let us know if this is what you're looking for.如果这就是您要找的,请告诉我们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM