1

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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

That's awesome. How would you adjust my original code to simply display the number of the month (1,2,...,12)?
For that you can convert months to factor and it should show 1, 2, ...12 instead of values like 2.5 7.5 etc.
There's no way of initially setting the x-axis variable to be discrete instead continuous?
months variable is continuous by converting it to factor we are making it to discrete.
I got the month numbers to work with factor. Thanks you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.