1

I am working with a time line, and for some reason I end up with a more or less random time-scale. Here we go:

df <- data.frame(balance=c(100,242,156,430,224),
  date = as.Date(c("2017-01-03", "2017-01-14", "2017-02-03", "2017-02-17", "2017-03-02")))

I us the following to plot:

plot(balance ~ date, df, type = "l", xaxt='n', xlab = "Date", 
                                 yaxt='n', ylab = "Balance [$]", main = "Personal finance")
axis(1, df$date, format(df$date, "%b %d"), cex.axis = .7, tick = FALSE, line=-0.5)

What I get is this:

enter image description here

How do I control the date axis? Instead of Jan 03, Jan 14, Feb 03, Feb 17, Mar 02 I would like Jan 01, Jan 15, Feb 01, Feb 15, Mar 01

Any help is appreciated!

M--
  • 25,431
  • 8
  • 61
  • 93

1 Answers1

2

You need to give those specific dates to your axis function; this works for you:

date_lab <- 
           as.Date(c("2017-01-01", "2017-01-15", "2017-02-01", "2017-02-15", "2017-03-01"))

plot(balance ~ date, df, type = "l", xaxt='n', xlab = "Date", 
                             yaxt='n', ylab = "Balance [$]", main = "Personal finance")
axis(1, date_lab, format(date_lab, "%b %d"), cex.axis = .7, tick = FALSE, line=-0.5)

enter image description here

If you use ggplot2 it usually makes the axis cleaner than base plot:

library(ggplot2)
ggplot(df, aes(x=date, y=balance))+geom_line()+
                                   labs(title = "Personal finance",
                                        x = "Date", y="Balance [$]")

enter image description here

M--
  • 25,431
  • 8
  • 61
  • 93