Search code examples
rggplot2bar-chartx-axis

R ggplot2 bar plot


I've linked together some code to create my current graph. My only problem is that my labels on the x-axis are being printed on top of each other. Does anyone know a solution? Also, is there a way I could organize my x-axis labels from greatest to smallest? Thanks. Here is the dataset I'm using:

    structure(list(Resort = c("Park City", "Powder Mountain", "Snowbird", 
    "Alta", "Snow Basin", "Deer Valley"), `Named Runs` = c(348, 154, 140, 116, 107, 103)), 
    row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))

Here is my code:

   library(readxl)
   library(ggplot2)
   library(dplyr)
   Utah_ski_resort_data_ <- read_excel("Desktop/Utah ski resort data..xlsx")

   View(Utah_ski_resort_data_)

   table(Utah_ski_resort_data_$Resort)
   table(Utah_ski_resort_data_$`Named Runs`)

   Utah_ski_resort_data_ %>% 
     ggplot(aes(x = Resort, y = `Named Runs`)) +
     geom_bar(stat = "identity")

Solution

  • I suggest to use reorder to sort, and rotating the labels to avoid overlaps:

    Utah_ski_resort_data_ <- structure(list(Resort = c("Park City", "Powder Mountain", "Snowbird", 
                              "Alta", "Snow Basin", "Deer Valley"), `Named Runs` = c(348, 154, 140, 116, 107, 103)), 
              row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
    library(ggplot2)
    library(dplyr)
    Utah_ski_resort_data_ %>% 
      ggplot(aes(x = reorder(Resort, -`Named Runs`), y = `Named Runs`)) +
      geom_bar(stat = "identity") + 
      theme(axis.text.x = element_text(angle = 60, hjust = 1))
    

    You find more info on these by entering ?reorder and ?ggplot2::element_text.