Home > Blockchain >  Distance between ticks in the X axis when plotting time-series in R
Distance between ticks in the X axis when plotting time-series in R

Time:08-12

I am trying to plot a time serie in R using the code below. I need to plot one tick by month but I obtain to many ticks. How can I solve this?

library(readxl)
dataset <- read_excel(choose.files())
dataset <- data.frame(dataset)
dataset$Inicio <- as.Date(dataset$Inicio, format=c("%d/%m/%Y"))


plot(Temp.media.de.las.medias ~ Inicio, dataset, col="black", ylim = c(0, 40), type = "l", lwd=2, xaxt='n')
axis(1, dataset$Inicio, format(dataset$Inicio, "%b %m"), cex.axis = .5)

grid(nx = NULL, ny = NULL,
     lty = 1,      # Grid line type
     col = "gray", # Grid line color
     lwd = 1)

enter image description here

Here my data:

dput(head(dataset$Temp.media.de.las.medias, 30))

c(25.36, 25.39, 23.6, 22.53, 23.59, 20.7, 18.99, 18.37, 17.46, 
16.13, 11.82, 14.52, 15.33, 13.39, 13.36, 13.41, 12.96, 10.85, 
8.68, 7.72, 6.04, 8.96, 12.35, 13.52, 11.41, 9.31, 9.72, 12.29, 
14.95, 14.64)

dput(head(dataset$Inicio, 30))

structure(c(17763, 17770, 17777, 17784, 17791, 17798, 17805, 
17812, 17819, 17826, 17833, 17840, 17847, 17854, 17861, 17868, 
17875, 17882, 17889, 17897, 17903, 17910, 17917, 17924, 17931, 
17938, 17945, 17952, 17959, 17966), class = "Date")

class(dataset$Temp.media.de.las.medias)
[1] "numeric"

class(dataset$Inicio)
[1] "Date"

CodePudding user response:

Thoughts:

base R

plot(Temp.media.de.las.medias ~ Inicio, dataset, col="black", ylim = c(0, 40), type = "l", lwd=2, xaxt='n')
ax <- as.Date(axTicks(1), origin = "1970-01-01")
axis(1, ax, format(ax, "%b %m"), cex.axis = .5)

base graphics, default spaced axis labels

Or if you prefer to have it year-aligned,

plot(Temp.media.de.las.medias ~ Inicio, dataset, col="black", ylim = c(0, 40), type = "l", lwd=2, xaxt='n')
ax <- seq(as.Date("2018-10-01"), as.Date("2019-04-01"), by = "3 months")
axis(1, ax, format(ax, "%b %m"), cex.axis = .5)

base graphics, axis labels on quarters

ggplot2

library(ggplot2)
ggplot(dataset, aes(Inicio, Temp.media.de.las.medias))  
  geom_line()  
  scale_x_date(date_labels = "%b %m")

ggplot2 with date labels


Data

dataset <- setDT(structure(list(Temp.media.de.las.medias = c(25.36, 25.39, 23.6, 22.53, 23.59, 20.7, 18.99, 18.37, 17.46, 16.13, 11.82, 14.52, 15.33, 13.39, 13.36, 13.41, 12.96, 10.85, 8.68, 7.72, 6.04, 8.96, 12.35, 13.52, 11.41, 9.31, 9.72, 12.29, 14.95, 14.64), Inicio = structure(c(17763, 17770, 17777, 17784, 17791, 17798, 17805, 17812, 17819, 17826, 17833, 17840, 17847, 17854, 17861, 17868, 17875, 17882, 17889, 17897, 17903, 17910, 17917, 17924, 17931, 17938, 17945, 17952, 17959, 17966), class = "Date")), row.names = c(NA,  -30L), class = c("data.table", "data.frame")))
  • Related