Claire Brereton
Claire Brereton

Reputation: 21

How can I control the date labels on my x axis using the 'plot' function?

I am plotting data from 1st Feb 2020 to 31st Dec 2020 i.e. 11 months worth. I have converted the x axis data from character to date format and it now shows six ticks labelled Mar, May, Jul, Sep, Nov, Jan which must be the default I want 11 ticks labelled Feb through Dec. I am pretty new to 'R' (obviously).

Upvotes: 0

Views: 945

Answers (2)

Allan Cameron
Allan Cameron

Reputation: 173793

Assuming your data and plot look like something this:

dates <- seq(as.Date("2020-02-01"), as.Date("2020-12-31"), by = "day")
values <- cumsum(rnorm(length(dates)))

plot(dates, values, type = "l")

Then we can plot with a blank axis using xaxt = "n" in our plot, then add a custom axis using axis, setting the x axis labels with at

plot(dates, values, type = "l", xaxt = "n")
axis.Date(1, dates, 
          at = seq(as.Date("2020-02-01"), as.Date("2020-12-01"), by = "1 month"))

Created on 2020-11-16 by the reprex package (v0.3.0)

Upvotes: 1

AudileF
AudileF

Reputation: 446

I assume you are using ggplot to for your data. If so you will need to format the style for the ticks. There are plenty of tutorials for this online. Here is a nice one https://www.r-bloggers.com/2018/06/customizing-time-and-date-scales-in-ggplot2/

You will see scale_x_date here, I beleive this is what you are looking for:

scale_x_date(date_breaks ="1 month")

Upvotes: 0

Related Questions