r - 减少饼图ggplot 2中的分类数
问题描述
我正在尝试详细说明饼图,我的数据是数字(1:61),我在导入数据集时将它们作为字符放置,而我的脚本是..
porcentaje<-review_a_r %>%
group_by(s_s) %>%
count() %>%
ungroup() %>%
mutate(percentage=`n`/sum(`n`) * 100)
ggplot(porcentaje, aes(x=1, y=percentage, fill=s_s)) +
geom_bar(stat="identity") +
geom_text(aes(label = paste0(round(percentage,1),"%")),
position = position_stack(vjust = 0.5)) +
coord_polar(theta = "y") +
theme_void()
我怎样才能只获得百分比> = 10%的类,而其他类在“其他”部分?
解决方案
考虑这种方法:
porcentaje <- porcentaje %>% mutate(flag = case_when(percentage <= 10 ~ "Other",
percentage > 10 ~ s_s))
在这里,我创建了一个新变量。case_when()实际上是一个向量化的 if/else,但我所做的是将百分比小于或等于 10 的任何东西分配给标志“其他”,而其他所有东西都分配一个等于 s_s 的标志。然后,您可以通过“标志”变量着色,即
ggplot(porcentaje, aes(x=1, y=percentage, fill=flag)) +
geom_bar(stat="identity") +
geom_text(aes(label = paste0(round(percentage,1),"%")),
position = position_stack(vjust = 0.5)) +
coord_polar(theta = "y") +
theme_void()