How to show every second R ggplot2 x-axis label value?

Léo Léopold Hertz 준영 picture Léo Léopold Hertz 준영 · Jul 17, 2017 · Viewed 14.6k times · Source

I want to show every second of x-axis label list in the presentation. Simplified code example in the following and its output in Fig. 1 where four Dates shown but #2 and #4 should be skipped.

# https://stackoverflow.com/a/6638722/54964
require(ggplot2)
my.dates = as.Date(c("2011-07-22","2011-07-23",
                     "2011-07-24","2011-07-28","2011-07-29"))
my.vals  = c(5,6,8,7,3)
my.data <- data.frame(date =my.dates, vals = my.vals)
plot(my.dates, my.vals)
p <- ggplot(data = my.data, aes(date,vals))+ geom_line(size = 1.5)

Expected output: skip dates second and fourth.

Actual code

Actual code where due to rev(Vars) logic, I cannot apply as.Date to the values in each category; the variable molten has a column Dates

p <- ggplot(molten, aes(x = rev(Vars), y = value)) + 
    geom_bar(aes(fill=variable), stat = "identity", position="dodge") + 
    facet_wrap( ~ variable, scales="free") +
    scale_x_discrete("Column name dates", labels = rev(Dates)) 

Expected output: skip #2,#4, ... values in each category. I thought here changing scale_x_discrete to scale_x_continuous and having a break sequence breaks = seq(1,length(Dates),2)) in scale_x_continuous but it fails because of the following error.

Error: `breaks` and `labels` must have the same length 

Proposal based Juan's comments

Code

ggplot(data = my.data, aes(as.numeric(date), vals)) + 
  geom_line(size = 1.5) +
  scale_x_continuous(breaks = pretty(as.numeric(rev(my.data$date)), n = 5)) 

Output

Error: Discrete value supplied to continuous scale

Testing EricWatt's proposal application into Actual code

Code proposal

p <- ggplot(molten, aes(x = rev(Vars), y = value)) + 
    geom_bar(aes(fill=variable), stat = "identity", position="dodge") + 
    facet_wrap( ~ variable, scales="free") +
    scale_x_discrete("My dates", breaks = Dates[seq(1, length(Dates), by = 2)], labels = rev(Dates))  

Output

Error: `breaks` and `labels` must have the same length 

If you have scale_x_discrete("My dates", breaks = Dates[seq(1, length(Dates), by = 2)]), you get x-axis without any labels so blank.

Fig. 1 Output of the simplified code example, Fig. 2 Output of EricWatt's first proposal

enter image description here enter image description here

OS: Debian 9
R: 3.4.0

Answer

Eric Watt picture Eric Watt · Jul 17, 2017

This works with your simplified example. Without your molten data.frame it's hard to check it against your more complicated plot.

ggplot(data = my.data, aes(date, vals)) + 
  geom_line(size = 1.5) +
  scale_x_date(breaks = my.data$date[seq(1, length(my.data$date), by = 2)])

Basically, use scale_x_date which will likely handle any strange date to numeric conversions for you.