SJJ
SJJ

Reputation: 53

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

Upvotes: 1

Views: 66

Answers (2)

zoowalk
zoowalk

Reputation: 2134

Like this?

library(tidyverse)
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"))

Utah_ski_resort_data_ %>% 
  ggplot(aes(x = reorder(Resort, -`Named Runs`),
             y = `Named Runs`)) +
  geom_bar(stat = "identity")+
  scale_x_discrete(guide = guide_axis(n.dodge = 2))+
  theme(axis.title.x=element_blank())

Created on 2020-12-02 by the reprex package (v0.3.0)

Upvotes: 2

lukeA
lukeA

Reputation: 54277

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.

Upvotes: 0

Related Questions