Search code examples
rggplot2axis-labelsgeom-bar

x-axis labels shifted off ggplot2 bar chart in r


I'm using geom_bar to plot the frequency of responses to a survey about introducing non-native species as pest control. I'm examining how responses to that question vary by where people live. Sample data here.

I want to customize x-axis labels on a bar-chart. However, in trying to specify new values, they either disappear or get completely shifted to the right. If I run the code as is, below, the x-axis is automatically populated with the pest.intro.nonnat values (-2, -1, 0, 1, 2), as in Fig. 1.

But if I activate scale_x_discrete() then I lose any x-axis labels (Fig. 2). If I activate xlim() then I get the labels I want, but they're bumped 4 spaces to the right (Fig. 3).

Can someone help me get my desired labels in the proper place? Thank you!

p + geom_bar(aes(fill = desc.p18), stat = "count",
             position = "stack", col = "black") +
  scale_fill_brewer(palette = "Dark2",
                    labels = legend,) + 
  # scale_x_discrete(labels = c("a", "b", "c", "d", "e")) +
  # xlim("a", "b", "c", "d", "e") +
  labs(title = "pest.intro.nonnat",
       y = "Number of responses") +
  theme(legend.title = element_blank(),
        legend.text = element_text(size = 10),
        axis.title.x = element_blank(),
        axis.text.x = element_text(size=10, angle=45))

Fig. 1 with no label specifications

Fig. 2 with scale_x_discrete specified

Fig 3. with xlim specified


Solution

  • Make sure that your x value are in factor if you wish to use scale_x_discrete.

    ggplot(dat, aes(x=as.factor(pest.intro.nonnat))) + 
      geom_bar(aes(fill = desc.p18), stat = "count", position = "stack", col = "black") +  
      scale_x_discrete(labels = c("a", "b", "c", "d", "e"))
    

    enter image description here