R语言ggplot2:按dataframe特定列给箱线图上色异常求助
问题:ggplot2箱线图分组异常,每个grp仅显示1个箱线图
我使用ggplot2生成箱线图,数据框df包含diff、grp、class三列,预期每个grp组对应2个不同颜色的箱线图(共6个),但实际仅生成3个。测试代码与样本数据如下:
df <- readxl::read_xlsx("~/Downloads/df_new_boxplot2.xlsx", sheet = 2, col_names = TRUE) p1 <- ggplot2::ggplot(df, aes(x = grp, y = diff, group = grp)) + geom_boxplot(aes(fill = class)) + xlab("") + ylab("diff") + theme( axis.title = element_text(size = 9), axis.text.x = element_text(size = 9), axis.text.y = element_text(size = 9) ) print(p1)
样本数据:
diff grp class 0.184258888 G1 ess 0.19497884 G1 ess 0.228319959 G1 ess -0.029457054 G1 non 0.167004668 G1 non 0.133294883 G1 non -0.350721613 G1 non -0.020916168 G2 non 0.061094133 G2 non 0.223643098 G2 non 0.18530414 G2 non -0.091747545 G2 non -0.183416747 G2 ess -0.123086067 G2 ess -1.158739554 G2 ess -0.002487487 G2 ess -0.405122069 G2 ess -0.023079965 G2 ess 0.348647385 G3 non 0.418440731 G3 non 0.584033387 G3 non 0.062912024 G3 non 0.731170886 G3 non 0.704519206 G3 non 0.554128995 G3 ess 0.401225253 G3 ess 0.026531873 G3 ess 0.332660319 G3 ess 0.014057467 G3 ess 0.463902969 G3 ess 0.149713663 G3 ess
解决方案
问题根源是手动设置group = grp,强制将同一grp下的所有数据归为一组,忽略了class的分组差异。要实现每个grp下显示2个不同颜色的箱线图,需按**grp与class的组合**分组,有两种简单修改方式:
方式1:移除手动group参数,让ggplot自动分组
ggplot会自动根据x(grp)和fill(class)的组合识别分组,无需手动指定:
p1 <- ggplot2::ggplot(df, aes(x = grp, y = diff)) + geom_boxplot(aes(fill = class)) + xlab("") + ylab("diff") + theme( axis.title = element_text(size = 9), axis.text.x = element_text(size = 9), axis.text.y = element_text(size = 9) ) print(p1)
方式2:手动指定group为双变量组合
通过interaction(grp, class)明确将两个变量的组合作为分组依据:
p1 <- ggplot2::ggplot(df, aes(x = grp, y = diff, group = interaction(grp, class))) + geom_boxplot(aes(fill = class)) + xlab("") + ylab("diff") + theme( axis.title = element_text(size = 9), axis.text.x = element_text(size = 9), axis.text.y = element_text(size = 9) ) print(p1)
两种方式都能生成预期的6个箱线图,每个grp下的ess和non分别以不同颜色展示。
内容的提问来源于stack exchange,提问作者Wasim Aftab
相关产品推荐
相关产品推荐

