user3426752 user3426752 - 1 month ago 12
R Question

scale_x_discrete() changes y axis

I am trying to set up a plot object and add data to it later. I am going to set up the two years of an election cycle and add in vertical lines at the point where key events happened. But my attempt to put vertical lines on the plot at six month intervals has instead put lines the y axis.

library(ggplot2)


dateline = seq(as.Date("2011/1/1"), by = "month", length.out = 24)
values = rnorm(24)


events = data.frame(dateline, values)


ggplot(events, aes(x=dateline, y=values)) +
scale_x_discrete(breaks=c("2011-01-01","2011-07-01","2012-01-01","2012-07-01")) +
labs(x="2012 Election Cycle")


The result is:
enter image description here

Now I think the lines should be on the x axis and be running up and down, no? And what is even stranger is that using scale_y_continuous() results in the behavior that I was expecting for x.

enter image description here

What makes this more confusing is that I was following a tutorial pretty closely where scale_x_discrete() behaves in the way I was expecting, i.e., creating vertical lines for the x axis. Am I losing my mind?

http://sharpsightlabs.com/blog/2014/11/24/r-line-chart-and-datavis-process/

Answer

You should use a continuous scale. This works for me:

ggplot(events, aes(x=dateline, y=values)) +     
  scale_x_date(date_breaks="6 months")     

More generally, simply:

ggplot(events, aes(x=dateline, y=values))

Will work in your case because the date range is such that ggplot automatically picks 6 months as the range of labels to show (this is why the y continuous scale example works for you; the y thing isn't doing anything, it is the removal of the scale_x_discrete bit that helps out).