2017-08-14 26 views
0

可以说我们有10000个用户分为2组:lvl beginner和lvl pro。ggplot2:通过其成员的小数比较2组

每个用户都有一个等级,从1将20

东风:

# beginers 
n <- 7000 
user.id <- 1:n 
lvl <- "beginer" 
rank <- sample(1:20, n, replace = TRUE, 
       prob = seq(.9,0.1,length.out = 20)) 
df.beginer <- data.frame(user.id, rank, lvl) 

# pros 
n <- 3000 
user.id <- 1:n 
lvl <- "pro" 
rank <- sample(1:20, n, replace = TRUE, 
       prob = seq(.9,0.3,length.out = 20)) 
df.pro <- data.frame(user.id, rank, lvl) 

library(dplyr) 
df <- bind_rows(df.beginer, df.pro) 
df2 <- tbl_df(df) %>% group_by(lvl, rank) %>% mutate(count = n()) 

问题1: 我需要柱状图比较并排各组方,但如果不是给我统计,我需要的百分比,因此,从各组棒将具有相同的最大HIGHT(100%)

我走到这一步的情节:

library(ggplot2) 
plot <- ggplot(df2, aes(rank)) 
plot + geom_bar(aes(fill=lvl), position="dodge") 

barplot

问题2:

我需要一个线图各组相比,所以我们将有2行,但如果不是给我统计,我需要的百分比,因此,从每个组的线路将有相同的最高HIGHT(100%)

我走到这一步的情节:

plot + geom_line(aes(y=count, color=lvl)) 

lines

问题3:

比方说,该行列是累积的,所以谁拥有秩3的用户也有秩1和2的用户谁具有秩20具有从1所有行列20.

所以,在绘图时,我希望剧情从拥有100%用户的排名1开始,排名2会少一些,排名少三等等。

我在画面上完成了所有这些工作,但我真的不喜欢它,并想向我展示R可以处理所有这些东西。

谢谢!

回答

3

三个问题,三种解决方案:

问题1 - 计算比例,并使用geom_col

df %>% 
    group_by(rank, lvl)%>% 
    summarise(count = n()) %>% 
    group_by(lvl) %>% 
    mutate(count_perc = count/sum(count)) %>% # calculate percentage 
    ggplot(., aes(x = rank, y = count_perc))+ 
    geom_col(aes(fill = lvl), position = 'dodge') 

enter image description here

问题2 - 几乎一样的问题1,区别在于使用geom_line代替geom_col

df %>% 
    group_by(rank, lvl)%>% 
    summarise(count = n()) %>% 
    group_by(lvl) %>% 
    mutate(count_perc = count/sum(count)) %>% 
    ggplot(., aes(x = rank, y = count_perc))+ 
    geom_line(aes(colour = lvl)) 

enter image description here

问题3 - 利用arrangecumsum

df %>% 
    group_by(lvl, rank) %>% 
    summarise(count = n()) %>% # count by level and rank 
    group_by(lvl) %>% 
    arrange(desc(rank)) %>% # sort descending 
    mutate(cumulative_count = cumsum(count)) %>% # use cumsum 
    mutate(cumulative_count_perc = cumulative_count/max(cumulative_count)) %>% 
    ggplot(., aes(x = rank, y = cumulative_count_perc))+ 
    geom_line(aes(colour = lvl)) 

enter image description here

+0

我很惊讶!谢谢!!! – erickfis