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
我想生成一个group
分组的箱线图。所以我想要一个带有K1
和K2
箱形图的图。我以为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)
对此我该怎么办?我也尝试过 x=samples
,但这是错误的。
编辑:也许这是另一个问题。但是,当我在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
答案 0 :(得分:0)
欢迎堆栈溢出Joris。
也许这就是您想要的:
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')
以下是输出:
让我们知道这是否是您想要的。