Jon Henner
Jon Henner

Reputation: 61

Discrete X Labels in ggplot2 do not end

I have some data taken from a Likert Survey. The scale of the survey is from 1 to 5. I am calculating the percentage of responses chosen for each question. My problem is when graphing these percentages, the boundary of the x-axis seems endless. This is the code I'm using to plot:

#Get the proportion table for the factored responses and melt it using the reshape2 package
#Graph it using the factor levels for X and the value converted into percentage for y

ggplot(melt(prop.table(table(factor(jsp.df$Q1, 
    levels =c(1, 2, 3, 4, 5))))),
    aes(x=Var1, y=value*100)) + 
geom_bar(stat="identity") + 
labs(title = "Q1: Deaf People Will be in College\n", x = "\nLikert Factors\n", y="Percent Circled\n") +
ylim(c(0,100)) +

#Replace factor levels with label names
scale_x_discrete(breaks=c(1, 2, 3, 4, 5), labels=c("Very Good \nChance", "Fairly Good \nChance", "Some \nChance", "A Little \nChance", "No \nChance"))

The results are attached. What would be the best way to fix the x axis? Thank you

Results

Upvotes: 2

Views: 4926

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98529

After melting your data of prop.table() Var1 values are integers not the factors because levels are 1,2,.... So in ggplot() call you need to use scale_x_continuous() instead of scale_x_discrete().

+ scale_x_continuous(breaks=c(1, 2, 3, 4, 5), 
                   labels=c("Very Good \nChance", "Fairly Good \nChance", 
                          "Some \nChance", "A Little \nChance", "No \nChance"))

Another way is to set limits= inside the scale_x_discrete(). For limits= you should use the same values as for breaks=.

+ scale_x_discrete(breaks=c(1, 2, 3, 4, 5), limits=c(1,2,3,4,5),
                   labels=c("Very Good \nChance", "Fairly Good \nChance", 
                      "Some \nChance", "A Little \nChance", "No \nChance"))

Upvotes: 5

Related Questions