Elisabeth
Elisabeth

Reputation: 3032

X-axis labels bunched together in R plot

I am using R to plot values, and am attempting to replace the x axis labels with my own as follows:

plot(date, value, xaxt="n", xlab="Year", ylab="value")
axis(1, at=seq(min(year), max(year), by=10))

where min(year) = 1969 and max(year) = 2016.

The plot itself looks fine, but the x axis tick labels are not:

plot with incorrect x axis tick labels

As you can see the x axis ticks are all bunched up together instead of being evenly spread across the x-axis and only showing one of the years.

What am I missing?

Thank you!!

My source data looks like this:

 site year       date  value
1  MLO 1969 1969-08-20 323.95
2  MLO 1969 1969-08-27 324.58
3  MLO 1969 1969-09-02 321.61
4  MLO 1969 1969-09-12 321.15
5  MLO 1969 1969-09-24 321.15
6  MLO 1969 1969-10-03 320.54

and the values are:

date <- data[["date"]]
value <- data[["value"]]
year <- data[["year"]]

Upvotes: 0

Views: 676

Answers (1)

r2evans
r2evans

Reputation: 161085

One problem is that you're treating factors of dates as if they are numerically relevant. Internally, a factor is just an integer, which means the fact that they plot sequentially is convenient but does not reflect the effective separation between the actual $dates.

Instead, convert them into actual Date objects and use that. (Due to small data, I changed the data slightly)

dat <- read.table(text='site year       date  value
  MLO 1969 1965-08-20 323.95
  MLO 1969 1968-08-27 324.58
  MLO 1969 1970-09-02 321.61
  MLO 1969 1972-09-12 321.15
  MLO 1969 1979-09-24 321.15
  MLO 1969 1983-10-03 320.54', header=TRUE, stringsAsFactors=FALSE)
dat$date <- as.Date(dat$date, format='%Y-%m-%d')

From here, (mostly) your plot.

plot(value ~ date, data=dat, type='b', xaxt="n", xlab="Year", ylab="value")
years <- as.Date(format(range(dat$date), "%Y-01-01"))
years <- seq(years[1], years[2], '5 years')
str(years)
#  Date[1:4], format: "1965-01-01" "1970-01-01" "1975-01-01" "1980-01-01"
axis(1, at=years, labels=format(years, '%Y'))
# or more directly (thanks @thelatemail)
axis.Date(1, years, format="%Y")

The reason I use both at and labels is so that we can get the value/location of a full Date object while preserving the printing-format of year-only.

simple datewise plot

Upvotes: 3

Related Questions