R语言 从函数向ggplot传递排序顺序参数

hlswsv35  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(121)
  • 我无法通过传递参数使ggplot按降序排序。我的函数要求“x_sort”的输入值为“yes”或“no”。如果是,我希望ggplot显示排序后的数据。*
score <- c(25,34,28,52,24,45,35,29)
status <- c("Poor", "Improved", "Excellent", "Poor","Poor", "Improved", "Excellent", "Poor")
df <- data.frame(score, status)

charts <- function(my_df, xvar, yvar, x_sort){
  if(x_sort=="yes") 
    ggplot(data=my_df,
    aes( 
      x=reorder(get(var), -get(score)),  
      y=get(yvar))) +
    geom_bar(stat='identity')+
    labs(x = xvar, y = yvar)       
  else 
  ggplot(data=my_df,
  aes( 
    x=get(xvar),  
    y=get(yvar))) +
  geom_bar(stat='identity')+
  labs(x = xvar, y = yvar)`
}

charts(df,"status","score","yes")
charts(df,"status","score","no")`

如果您发送“no”,则此操作有效,但如果您发送“yes”来告诉它进行排序,则无效。

bz4sfanl

bz4sfanl1#

我们可以使用.data而不是get进行子集划分-此外,检查拼写错误var而不是x_var,并使用get(score)(应为score

charts <- function(my_df, xvar, yvar, x_sort){
  if(x_sort=="yes") 
    {
    ggplot(data=my_df,
    aes( 
      x=reorder(.data[[xvar]], -score),  
      y=.data[[yvar]])) +
    geom_bar(stat='identity')+
    labs(x = xvar, y = yvar)  
  } else {
  ggplot(data=my_df,
  aes( 
    x=.data[[xvar]],  
    y=.data[[yvar]])) +
  geom_bar(stat='identity')+
  labs(x = xvar, y = yvar)
}
}
  • 测试
charts(df,"status","score","yes")
charts(df,"status","score","no")

相关问题