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