ggplot2分面内箱线图重排辅助函数失效问题求助
问题:ggplot2分面箱线图按均值排序异常排查
我参考Stack Overflow上《How to properly sort facet boxplots by median?》一文,使用两个辅助函数尝试在ggplot2中按均值升序重排分面内的箱线图,但运行后生成了异常图形,恳请帮忙排查问题所在。
代码
library(ggplot2) library(agricolae) library(tidyr) library(tidyverse) #FULL DATA SET LOADING WITH REPLICATES totalstarch2 = read.csv("totalstarch3.csv", header = TRUE, stringsAsFactors = T) totalstarch2$locyear = as.factor(paste(totalstarch2$location," ",totalstarch2$year,sep='')) View(totalstarch2) str(totalstarch2) #helper functions for reordering within facet reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) { new_x <- paste(x, within, sep = sep) stats::reorder(new_x, by, FUN = fun) } scale_x_reordered <- function(..., sep = "___") { reg <- paste0(sep, ".+$") ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...) } #draw box plot with genotype as facets a=ggplot(totalstarch2,aes(x=reorder_within(starchdry,locyear, genotype), y=starchdry, color=locyear))+ geom_point()+ geom_boxplot()+ facet_wrap(~genotype, scales= "free_x", nrow=1, ncol=10)+ scale_y_continuous("Total starch % (dry basis)",limits = c(20,70), breaks = seq(20,70,5))+ theme_classic()+ theme(panel.background = element_rect(fill = NA, color = "black"))+ scale_x_discrete("Environment")+ labs(color="Environment", title="A")+ theme(axis.title = element_text(size=14, color="black"), axis.text = element_text(size=10, color="black"), axis.text.x = element_text(angle=45, hjust=1), legend.title = element_text(size=14), legend.text = element_text(size=10), title =element_text(size=14, face='bold')) a
效果对比
当前异常效果

理想效果

数据集说明
使用的数据集为totalstarch3.csv,包含重复试验数据,已添加locyear因子列(由location和year拼接而成)。
内容的提问来源于stack exchange,提问作者Maany Ramanan
相关产品推荐
相关产品推荐

