首页 > 解决方案 > top_n() 没有选择 n

问题描述

目标:按降序绘制前 20 个国家/地区

问题:在使用该top_n功能时,它坚持选择所有而不是只选择前20名。

这是我的代码:

#Omit missing values
na.omit(kiva_loans)%>%
  #Group by country label
  group_by(country_code)%>%
  dplyr::count(country_code, sort = TRUE)%>%
  top_n(20)%>%
   ggplot(aes(reorder(x=country_code,n),y=n))+
   geom_col(position="dodge",
            color = "black",
            fill="purple")+
   coord_flip()

在该top_n(20)行之后,输出为:

在此处输入图像描述

这表明它并没有在 20 岁时将其切断。这反过来又是可怕的情节:

在此处输入图像描述

标签: rdplyrtop-n

解决方案


#Omit missing values
na.omit(kiva_loans)%>%
  #Group by country label
  group_by(country_code)%>%
  dplyr::count(country_code, sort = TRUE)%>%
  ungroup() %>% # add this to ungroup
  top_n(20)%>%
   ggplot(aes(reorder(x=country_code,n),y=n))+
   geom_col(position="dodge",
            color = "black",
            fill="purple")+
   coord_flip()

ungroup()在你打电话之前top_n

?top_n你可以读到这个:

n 要返回的行数。如果 x 被分组,则这是每组的行数。如果有平局,将包括多于 n 行。


推荐阅读