top_n() 未选择 n

top_n() not selecting 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 时切断它。这又是可怕的情节:

#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()

在您致电 top_n

之前 ungroup()

您可以从 ?top_n 阅读到:

n number of rows to return. If x is grouped, this is the number of rows per group. Will include more than n rows if there are ties.