在R中绘制分组数据及其百分比

时间:2017-07-05 17:36:19

标签: r plot ggplot2 bar-chart

我的数据采用此格式

public GenericResponse handleConfirmation(UserInteraction userInteraction, AppointmentInfo apptInfo, ResponseType responseType) 

我只知道基本情节,所以我用

df$new  df$y
0.5     A
0.0     D
1.0     D
1.0     M
1.0     A
1.0     MNY
1.0     NO
0.0     NO
1.0     PV
0.5     PV
1.0     S
0.0     S

但是在X轴中应该有唯一值,我该怎么做到这一点?他们的百分比

百分比应在其中。 例如:A = 1.5 / 2 => 75%

2 个答案:

答案 0 :(得分:1)

或者,您可以使用aggregate在基准R中执行此操作。

Tab1 = aggregate(df$new, list(df$y), sum)
Tab1$x = Tab1$x / aggregate(df$y, list(df$y), length)$x
barplot(Tab1$x, names.arg=Tab1$Group.1)

答案 1 :(得分:0)

我不确定你想要的百分比是什么,但是这里是一个计算数据框中这些百分比的解决方案,并且还创建了y的每个唯一值的计数的条形图。关键在于as.factor(y)


library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)

df <- data.frame(new = c(0.5, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.5), 
                 y = c("A", "D", "D", "M", "A", "MNY", "NO", "NO", "PV"))

df$y<- as.factor(df$y)

df <- df %>%
  group_by(y) %>%
  mutate(avg = mean(new))

df
#> # A tibble: 9 x 3
#> # Groups:   y [6]
#>     new      y   avg
#>   <dbl> <fctr> <dbl>
#> 1   0.5      A  0.75
#> 2   0.0      D  0.50
#> 3   1.0      D  0.50
#> 4   1.0      M  1.00
#> 5   1.0      A  0.75
#> 6   1.0    MNY  1.00
#> 7   0.0     NO  0.50
#> 8   1.0     NO  0.50
#> 9   0.5     PV  0.50

ggplot(data = df) +
    geom_bar(aes(x = y))