hanwick1
hanwick1

Reputation: 73

How to create a placeholder for empty factor levels on a bar chart axis using ggplot2?

I have some survey data, from which I would like to simply graph the frequency of each response per question.

My code

library(ggplot2)

Df1 # data frame with 3 variables: Provider, Question, Score

Df1$Score <- factor(Df1$Score, levels = c(0,1,2,3))

# Plot
q <- qplot(Score, data = Df1, facets = .~Provider, geom="bar", fill=Provider)

q + labs(title = wrapper(Question, width = 70), x = "Score", y = "Frequency")   # Add title and axes labels

And the result is this: enter image description here

Which is great but as I will be generating a few of these graphs, it would visually easier to interpret if there was a space for '1' on the x-axis too.

I have spent a lot of time trying various combinations scale_x_discrete, labels, breaks and reorder but I've still not been able to generate an elusive placeholder.

Is there an easy way to force ggplot2 to plot an empty factor?

Upvotes: 3

Views: 3554

Answers (2)

akuiper
akuiper

Reputation: 214917

You can also use the limits parameter in the scale_x_discrete function to hold the place, here is a dummy example:

df
  month count
1   Jan     1
2   Feb     2
3   Mar     3
ggplot(df, aes(x = month, y = count)) + 
       geom_bar(stat = "identity") + 
       scale_x_discrete(limits = c("Jan", "Feb", "Mar", "Apr"))

enter image description here

Upvotes: 3

lukeA
lukeA

Reputation: 54237

Since you didn't provide a full reproducible example:

ggplot(mtcars, 
            aes(factor(gear, levels = 1:5), 
                mpg)) +
  geom_point() + 
  scale_x_discrete(drop=F)

Use drop=FALSE to keep unused factor levels.

Upvotes: 8

Related Questions