我的数据框如下所示:
plant distance
one 1
one 3
one 2
one 3
one 7
one 4
one 6
one 8
one 9
two 1
two 6
two 4
two 8
two 5
two 3
three ……
我希望按时间间隔将每个级别的distance
分成组(例如,interval = 3)。
plant distance group
one 1 1
one 3 1
one 2 1
one 3 1
one 7 3
one 4 2
one 6 2
one 8 3
one 9 3
two 1 1
two 6 2
two 4 2
two 8 3
two 5 2
two 3 1
three ……
计算每组的百分比
plant group percentage
one 1 0.44
one 2 0.22
one 3 0.33
two 1 0.33
two 2 0.50
two 3 0.17
three ……
最后,绘制每组的每个级别的百分比,如下所示:
我不知道如何按间隔分割每个级别。对不起我的英语不好!谢谢你的帮助!
答案 0 :(得分:1)
以下是使用dplyr
执行此操作的一种方法:
library(dplyr)
library(ggplot2)
my_data %>%
mutate(group = factor(cut(distance, seq(0, max(distance), 3), F))) %>%
group_by(plant, group) %>%
summarise(percentage = n()) %>%
mutate(percentage = percentage / sum(percentage)) %>%
ggplot(aes(x = plant, y = percentage, fill = group)) +
geom_bar(stat = "identity", position = "stack")