带有R的计数的频率图

时间:2017-04-26 22:46:43

标签: r plot

我尝试做的频率图是

  • 每个栏上方有数量的条形图
  • 左侧的相对频率
  • 右侧的累积频率

数据集是

dput(x2)
c(1L, 5L, 3L, 3L, 5L, 3L, 4L, 1L, 2L, 2L, 7L, 3L, 2L, 2L, 3L, 
3L, 2L, 1L, 5L, 4L, 4L, 3L, 5L, 2L, 6L, 2L, 1L, 2L, 5L, 5L, 5L, 
3L, 6L, 4L, 5L, 4L, 6L, 7L)

频率分布

table(x2)
x2
1 2 3 4 5 6 7 
4 8 8 5 8 3 2 

相对频率

prop.table(table(x2))
x2
         1          2          3          4          5          6          7 
0.10526316 0.21052632 0.21052632 0.13157895 0.21052632 0.07894737 0.05263158 

编辑:如下图所示,但右侧的累计频率,左侧的相对频率和计数条 enter image description here

1 个答案:

答案 0 :(得分:2)


library(tidyverse)
library(broom)

table(x2) %>% 
  tidy() %>%
  mutate(rel_freq = Freq/sum(Freq), sum = sum(Freq)) %>%
  ggplot(aes(reorder(x2, Freq), rel_freq)) + 
  geom_col() + 
  geom_text(aes(label = Freq), vjust = -.5) +
  scale_y_continuous(sec.axis = sec_axis(~.*length(x2)))