Select and plot top frequencies with dplyr

后端 未结 1 1754
后悔当初
后悔当初 2021-01-27 01:06

The objective is to select/filter top 3 (or n) events that have the largest frequencies (occurrences) in a dataframe then plot these using a barplot in ggplot2.

The exam

相关标签:
1条回答
  • 2021-01-27 01:46

    After we order the dataset based on the 'freq' column (arrange(...)), we can the top 3 values with slice, use ggplot, specify the 'x' and 'y' variables in the aes, and plot the bar with geom_bar

     library(ggplot2)
     library(dplyr)
     df %>% 
        arrange(desc(freq)) %>%
        slice(1:3) %>%
        ggplot(., aes(x=type, y=freq))+
                  geom_bar(stat='identity')
    

    Or another option is top_n which is a convenient wrapper that uses filter and min_rank to select the top 'n' (3) observations in 'freq' column and use ggplot as above.

    top_n(df, n=3, freq) %>%
              ggplot(., aes(x=type, y=freq))+
                  geom_bar(stat='identity')
    

    0 讨论(0)
提交回复
热议问题