R语言 使用另一列的值对方面级别进行排序

kqlmhetl  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(178)

这是我的数据的一部分。我有一个很长的格式3因子水平和20个变量。

str(Data_Penelitian2) 
tibble [540 × 5] (S3: tbl_df/tbl/data.frame)
 $ Zonation        : chr [1:540] "PRG" "PRG" "PRG" "PRG"  "PRG" ... "GWM" "GWM" .. "GWH" "GWH"..
 $ Variables       : chr [1:540] "WT (%)" "WT (%)" "Wt (%)" "pH" "pH" "pH" "Corg" "Corg" "Corg" ...
 $ Value           : num [1:540] 352 723 1084 4.8 5.5 4.2 47.8 48.2 41.6...
 $ ID              : num [1:540] 1 1 1 2 2 2 3 3 3 ... 20

我基于变量对值和分区因子的箱线图+小提琴图进行了分面。但这些面是按字母顺序排列的。所以我为每个变量分配ID来对facet进行排序。基本上,我想用“变量”来分面,但用“ID”来排序。我正在尝试facet_wrap,避免手动排序(像这样:Fixing the order of facets in ggplot或此:How do I get ggplot to order facets correctly?),因为我有20个唯一的变量名。

calc_stat <- function(x) {
  coef <- 1.5
  n <- sum(!is.na(x))
  # calculate quantiles
  stats <- quantile(x, probs = c(0.1, 0.25, 0.5, 0.75, 0.9))
  names(stats) <- c("ymin", "lower", "middle", "upper", "ymax")
  return(stats)
}

windowsFonts(Times=windowsFont("Times New Roman"))

p <- ggplot(Data_Penelitian2, aes(x=Zonation, y=Value)) + 
    geom_violin(trim=FALSE) + 
    stat_summary(fun.data = calc_stat, geom="boxplot",alpha = 0.2, width = 0.2 ) +  
    geom_jitter(width = 0.3, alpha = 0.5, aes(color = Zonation))+
    facet_wrap(factor(Data_Penelitian2$Variables~., levels = unique(Data_Penelitian2$ID)),scales="free", ncol=4) +
  # scale_fill_viridis(discrete = TRUE,  option = "turbo", alpha=0.7)+
   theme_minimal()+ theme(text=element_text(family="Times")) +
    theme(legend.position = "none")

facet_wrap不工作。有什么建议吗?

kiayqfof

kiayqfof1#

我通过创建labeller函数并将其传递给ggplot 2找到了诀窍。感谢@naught101的回复https://stackoverflow.com/a/12104207/17292783

calc_stat <- function(x) {
  coef <- 1.5
  n <- sum(!is.na(x))
  # calculate quantiles
  stats <- quantile(x, probs = c(0.1, 0.25, 0.5, 0.75, 0.9))
  names(stats) <- c("ymin", "lower", "middle", "upper", "ymax")
  return(stats)
}

varNames = list(
'1'="WT (%)",
'2'="pH",
'3'="C-org (%)",
'4'="AC (%)",
'5'="CNR"
)

var_labeller <- function(variable,value){
  return(varNames[value])
}
p <- ggplot(Data_Penelitian2, aes(x=Zonation, y=Value)) + 
    geom_violin(trim=FALSE) + 
    stat_summary(fun.data = calc_stat, geom="boxplot",alpha = 0.2, width = 0.2 ) +  
    geom_jitter(width = 0.3, alpha = 0.5, aes(color = Zonation))+
    facet_wrap(ID~., labeller=var_labeller, scales="free", ncol=4,) +
  # scale_fill_viridis(discrete = TRUE,  option = "turbo", alpha=0.7)+
   theme_minimal()+ theme(text=element_text(family="Times")) +
    theme(legend.position = "none")

相关问题