hopefullyphdsoon
hopefullyphdsoon

Reputation: 41

Changing Month (from Number) to Full Month Name in R

I'm not sure if I missed it explained elsewhere but I need some help changing the month number (ex. 1, 2, 3) to month name (ex. January, February, March).

Currently, the graph prints the number of the month on the x-axis and I would like for it to show the name of the month.

I did try a few items but kept getting null in the column.

Below is my current code:

install.packages("Stat2Data")
library(Stat2Data)
data("CO2Hawaii")

select(CO2Hawaii)

hawaiiGraph <- 
  ggplot(
    data = CO2Hawaii, 
    aes(
      x = Month, 
      y = CO2)
    ) +
  geom_line(
    aes(group = Year)
    ) +
  theme(axis.text.x = element_text(angle = 55, hjust = 1)
    ) +
  ggtitle("CO2 Levels in Hawaii Over Time")
  
hawaiiGraph

I really appreciate any help.

Upvotes: 4

Views: 3389

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76432

The Month is a numeric column so the trick is to label the x axis with the built-in variable month.name with breaks vector 1:12. This is done in scale_x_continuous.
Note also that it's not necessary to load a package to access one of its data sets.

library(ggplot2)

data("CO2Hawaii", package = "Stat2Data")

hawaiiGraph <- ggplot(
  data = CO2Hawaii,
  mapping = aes(
    x = Month, 
    y = CO2)
) +
  geom_line(
    aes(group = Year)
  ) +
  scale_x_continuous(
    breaks = seq_along(month.name), 
    labels = month.name
  ) +
  theme(
    axis.text.x = element_text(angle = 55, hjust = 1)
  ) +
  ggtitle("CO2 Levels in Hawaii Over Time")

hawaiiGraph

enter image description here

If the month name is too long, month.abb gives you the same result but with an abbreviated month name (e.g. Jan instead of January).

Upvotes: 6

Related Questions