Search code examples
rggplot2axis-labels

ggplot2: Missing x labels after expanding limits for x axis?


I imagine that my question is trivial, but I can't figure it out. I have an yearly data which I want to display using ggplot2 barplot. As my bar for the first year is too close to y axis, I want to expand limits of x axis. However, if applied, my X axis values disappear, even theme() specification does't produce results.. and I don't understand why? Could the reason be that I am using "years" as factors? But for bar representation I need to use discrete scale...

Thank you !

# reproductible exemple

year<-c(2003:2010)
manag<-rep(c("A", "B"), 4)
np<-rep(c(0,1), each = 4)
val<- c(10,20,50,10,14,80,19,25)

df<-data.frame(cbind(year, 
                     manag, np, val))

require(ggplot2)

a<-ggplot(data = df, aes(x = as.factor(year), y = val)) + 
  ggtitle("MISSING X VALUES!!!") +
  geom_bar(stat = "identity") +
  scale_x_discrete(limits= c(2002:2015)) 
  # theme(axis.text.x=element_text(size = 8, colour = "black", angle = 90)

b<-ggplot(data = df, aes(x = as.factor(year), y = val)) +
  geom_bar(stat = "identity") +
  ggtitle("NOT EXPANDED X LIMITS")

grid.arrange(a, b, ncol = 2)

enter image description here


Solution

  • First your data.frame code needs cleaned. Remove the cbind - cbind is turning everything into a factor

      df<-data.frame(cbind(year, 
                      manag, np, val))
    

    so that it looks like

      df <- data.frame(year, manag, np, val))
    

    Then the x-axis will be on a continuous scale e.g.

    ggplot(df, aes(year, val))+geom_bar(stat="identity")+ 
      scale_x_continuous(breaks = c(2002:2010), 
                         labels = factor(2002:2010), 
                         limits = c(2002,2011)) 
    

    You can change the labels to something like

    labels = c("", factor(2003:2010))
    

    if you don't want the 2002 in there