R中的分组箱线图 [英] Grouped boxplot in R
本文介绍了R中的分组箱线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
df<-data.frame(值= c(2.5,12,4.8,56,78),样本= c('45fe.K2','59ji.K2','59rc.K1','45hi.K1','96hu.K1'),group = c('K2','K2','K1','K1','K1'))df值样本组1 2.5 45fe.K2 K22 12.0 59ji.K2 K23 4.8 59rc.K1 K14 56.0 45hi.K1 K15 78.0 96hu.K1 K1
我想生成一个 group
分组的箱线图.所以我想要一个带有 K1
和 K2
箱形图的图.我认为这
让我们知道这是否是您想要的.
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. So I want one plot with a K1
and K2
boxplot. 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
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.
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
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.
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.
这篇关于R中的分组箱线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文