0

I am trying to make a basic histogram with ggplot, showing the distribution of students who chose one of four instructor profiles as their first preference for a particular course. So in other words, students read: "When taking course "X", rank which instructor type (4 different professor types/profiles) that you would prefer teach the class." As a first jab, I wanted to make a histogram showing the distribution of students' first instructor preference. The problem I am running into, however, is that no one chose instructor number 4. I think it is visually important to show that no one chose 4. But in geom_histogram, it doesn't include 1, 2, 3, and 4 as integers on the X-axis. Here is the code I am using:

ggplot(data = Preference, aes(Preference$First_FTF)) +
  geom_histogram(binwidth = 0.25, boundary = 0, close = "left") + 
  scale_x_continuous(breaks = 1:4)

Any suggestions? It'd be nice to have 1, 2, 3, and 4 on the X-axis.

enter image description here

Richard Telford
  • 9,558
  • 6
  • 38
  • 51
bjk127
  • 51
  • 5
  • 3
    You can use the limits argument in scale_x_continuous. Also, don't use the $ notation inside aes – Richard Telford Aug 23 '18 at 21:11
  • A side note: since you have an inherently categorical variable on the x-axis ("instructor type") you should probably use a discrete scale rather than a continuous one. – Mikko Marttila Aug 24 '18 at 07:14

2 Answers2

0

You can set the range of an axis by using the limits argument in scale_x_continuous or scale_y_continuous. In your example:

ggplot(data = Preference, aes(Preference$First_FTF)) +
      geom_histogram(binwidth = 0.25, boundary = 0, close = "left") + 
      scale_x_continuous(limits = c(1,4))
Vishesh Shrivastav
  • 2,079
  • 2
  • 16
  • 34
  • How is this different from @RichardTelford's answer in the comment section? – Maurits Evers Aug 23 '18 at 21:52
  • 1
    This worked! Thank you! – bjk127 Aug 23 '18 at 21:53
  • 1
    @MauritsEvers I hadn't read the comment. My bad :/ – Vishesh Shrivastav Aug 23 '18 at 22:03
  • 1
    @MauritsEvers I'd say it's different in the sense that it's an answer, not a comment. Answers-as-comments without also closing the question are problematic because they leave questions as "open" even though they really have been answered. – Mikko Marttila Aug 24 '18 at 07:18
  • 1
    @MikkoMarttila While I generally agree with you on the answers-as-comments notion, courtesy and SO etiquette would've supported a request for RichardTelford to turn his comment into an answer, rather than re-posting his comment-answer as an independent answer to "claim the points". – Maurits Evers Aug 24 '18 at 08:59
0

xlim and ylim can be used on ggplot to apply limits on the chart area -

ggplot(data = Preference, aes(Preference$First_FTF)) +
  geom_histogram(binwidth = 0.25, boundary = 0, close = "left") + 
  xlim(1, 4)
RobJan
  • 1,351
  • 1
  • 14
  • 18