AK47
AK47

Reputation: 1328

fixed x axis values in ggplot

I am using data frame DF (simple generated example):

Month <- c(1,2,3,5,8,9,6,3,2,2,12,12)
Brand <- c("Brand4","Brand5","Brand13","Brand62","Brand2","Brand1","Brand12","Brand12","Bra    nd62","Brand55","Brand2","Brand1")
USD <- abs(rnorm(12))*100
DF <- data.frame(Month, Brand, USD)

to plot a graph with qplot, which looks like this:

enter image description here

qplot(as.factor(Month), USD, data=DF, fill=Brand,
  stat="summary", fun.y="sum", geom="bar",
  main = "Graph", xlab = "Month", ylab = "USD") 

In X axis I have months. However, 4, 8, 10 and 11 months are missing. I'd like to show seasonality of the data, so X axis should include all 12 months. Is it possible to fix X axis with numbers 1 to 12, that X axis would also show missing months with empty bars?

Is it possible to do with qplot function or should I use anything else?

Upvotes: 1

Views: 3471

Answers (1)

akrun
akrun

Reputation: 887901

We can use ggplot with scale_x_discrete.

library(ggplot2)
ggplot(DF, aes(x=factor(Month,levels=1:12), y=USD, fill=Brand))+
           geom_bar(stat='identity')+
           scale_x_discrete('Month', breaks=factor(1:12), drop=FALSE)

enter image description here

NOTE: The data is slightly different as we didn't use set.seed

Upvotes: 4

Related Questions