百分比条形图

时间:2020-06-22 07:02:58

标签: r

样本数据:

a <- data.frame()
a <- cbind(sample(1:4, 100,replace = T))
a <- cbind(a,sample(0:1, 100,replace = T))
colnames(a) <- c("Group","Event")

我想显示一个条形图,其中X轴是组,Y轴是每个组中事件百分比的百分比,而组N则位于图中。 我也希望按高度排序。

我似乎无法解决这个问题,有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

只是让您入门

a %>% 
    dplyr::as_tibble() %>%
    dplyr::group_by(Group) %>%
    dplyr::summarise(PCT=sum(Event)/dplyr::n(),
                     N=dplyr::n(),
                     LABEL=paste("N=",N)) %>%
    ggplot2::ggplot(ggplot2::aes(x=Group,y=PCT,label=LABEL)) + 
    ggplot2::geom_col() +
    ggplot2::geom_label()

enter image description here

a %>% 
    dplyr::as_tibble() %>%
    dplyr::mutate(Event=as.factor(Event)) %>%
    ggplot2::ggplot(ggplot2::aes(x=Group,fill=Event)) + 
    ggplot2::geom_bar(position="fill") 

enter image description here