Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading