Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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.

like image 698
hopefullyphdsoon Avatar asked Oct 18 '25 07:10

hopefullyphdsoon


1 Answers

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

like image 171
Rui Barradas Avatar answered Oct 19 '25 20:10

Rui Barradas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!