Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in R Programming by (50.2k points)

I am having the following sample data:

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")

I want to plot a barplot where the X-axis is the group, and the Y-axis is of the percentage of events in each group, with the N of the group in the plot itself. How to plot?

1 Answer

0 votes
by (108k points)

You can implement the following in R programming:

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()

a %>% 

    dplyr::as_tibble() %>%

    dplyr::mutate(Event=as.factor(Event)) %>%

    ggplot2::ggplot(ggplot2::aes(x=Group,fill=Event)) + 

    ggplot2::geom_bar(position="fill") 

Browse Categories

...