目标:按降序绘制前 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()
Run Code Online (Sandbox Code Playgroud)
在该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()
Run Code Online (Sandbox Code Playgroud)
就ungroup()在你打电话之前top_n
从?top_n你可以读到这个:
n 要返回的行数。如果 x 已分组,则这是每组的行数。如果有关系,将包括多于 n 行。