Search code examples
rggplot2geom-bar

How can I show only Top 10 of this geom_bar graph? (ggplot, R)


library(nycflights13)
library(tidyverse)
plot_2 <- flights %>%
  filter(origin == "JFK",
  month %in% c(7, 8, 9),
  !is.na(dep_time)) %>%
  left_join(airports %>%
  select(faa, name),
  by=c("dest"="faa"))
  
options(repr.plot.width = 9, repr.plot.height = 6)

plot_2 %>%
  ggplot(aes(y = reorder(name, name,
  function(y) + length(y)))) +
  geom_bar(fill = "#4e0090") +
  theme_minimal() +
  labs(title = "Top Destinations people traveled to the most (summer 2013)",
  x = "Count",
  y = "Name",
  caption = "Source: Package 'nycflights13'") +
  theme(plot.title = element_text(hjust = -0.15)) +
  expand_limits(x = c(0, 2900))

I did try top_n() but it didn't work, or I don't know how to deal with these data structures. Thanks for your answer!


Solution

  • I would probably do the manipulation before passing the data to ggplot2.

    Assuming your data comes from the nycflights13 package, the following should be completely reproducible

    library(tidyverse)
    
    nycflights13::flights %>%
      filter(origin == "JFK",
             month %in% c(7, 8, 9),
             !is.na(dep_time)) %>%
      left_join(nycflights13::airports %>%
                  select(faa, name), by=c("dest"="faa")) %>%
      filter(!is.na(name)) %>%
      count(name) %>%
      mutate(name = reorder(name, n)) %>%
      top_n(10) %>%
      ggplot(aes(y = name, x = n)) +
      geom_col(fill = "#4e0090") +
      theme_minimal() +
      labs(title = "Top Destinations people traveled to the most (summer 2013)",
           x = "Count",
           y = "Name",
           caption = "Source: Package 'nycflights13'") +
      theme(plot.title = element_text(hjust = -0.15)) +
      expand_limits(x = c(0, 2900))
    #> Selecting by n
    

    enter image description here

    Created on 2023-02-20 with reprex v2.0.2