0
votes

I have the following dataframe:

months = c(1,2,3,4,5,6,7,8,9,10,11,12)        
totals = c(437318,406597,454125,432062,443323,414061,418627,428530,400509,427900,378849,344718)
test_df = data.frame(months, totals)

enter image description here

I created a plot using the following code:

test_df %>%
  ggplot(aes(x=months, y=totals)) +
  geom_bar(stat='identity', fill='red3') +
  scale_y_continuous(breaks=scales::breaks_extended(n=10)) +
  ggtitle('Amount by Month') +
  ylab('Amount') +
  xlab('Month')

enter image description here

ggplot is assuming that the x-axis contains a continuous variable. I assume this is because the test_df$months is of integer type. I tried editing my plot code by first creating an array of month names:

months = c('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')

and then adding this to the plot code:

scale_x_discrete('Month', months)

but this didn't work.

How can I get the x-axis to be displayed with either integer values for the month or month names?

1

1 Answers

1
votes

You can use the inbuilt vector month.abb :

library(dplyr)
library(ggplot2)

test_df %>%
  mutate(months = factor(month.abb[months], levels = month.abb)) %>%
  ggplot(aes(x=months, y=totals)) +
  geom_bar(stat='identity', fill='red3') +
  scale_y_continuous(breaks=scales::breaks_extended(n=10)) +
  ggtitle('Amount by Month') +
  ylab('Amount') +
  xlab('Month')

enter image description here