2

My (minimal reproducible) code shows two possibilities for scale_x_datetime.

Without the lables specifier I get tick labels in the format yyyy-mm-dd. I don’t want the year in the tick label, as the year is used in the start and end dates in the title.

However, when I use the labels specifier the tick labels show the last day of the month.

How do I get the tick labels, without the year, at the first day of the month.

Thank you.

enter image description here

enter image description here

library(ggplot2)
library(scales)

mydata <- read.table(header = TRUE, text = "
            dates values
            2022-12-03 5
            2023-03-02 0
            ")

plottib <- tibble(mydata) %>% 
  mutate(dates = as.POSIXct(dates,format="%Y-%m-%d") )  

start_date <- min(mydata$dates) 
end_date <- max(mydata$dates) 

gp <- ggplot( plottib , aes( x=dates, y=values )) +
  geom_point() +
  labs(title = paste("From", start_date, 'to', end_date, sep=' ') ) +
  
  scale_x_datetime(date_breaks = "1 month")   `a`

 # scale_x_datetime(date_breaks = "1 month", labels = date_format("%d %b") ) 

gp
tjebo
  • 21,977
  • 7
  • 58
  • 94
donman
  • 57
  • 3
  • related https://stackoverflow.com/questions/42762138/setting-x-axis-limits-for-datetime-in-ggplot and https://stackoverflow.com/questions/14759676/specification-of-first-and-last-tick-marks-with-scale-x-date – tjebo Feb 22 '23 at 10:51

2 Answers2

2

When you convert the "Dates" to "POSIXct", you have to specify the timezone:

plottib <- tibble(mydata) %>% 
  mutate(dates = as.POSIXct(dates, format="%Y-%m-%d", tz="UTC") )  

This results in:

enter image description here

Edward
  • 10,360
  • 2
  • 11
  • 26
  • Thank you Edward, this solves the problem I posted. However, in my non-minimal real application I still get the end of month tick labels. I will therefore have to dig deeper to determine why this is the case. – donman Feb 22 '23 at 08:46
  • Can you edit your post and add a few more records? Or use `dput(mydata[1:200,])`. – Edward Feb 22 '23 at 09:20
0

Thank you @Edward for your suggestions, which I tried, but no luck. I felt obliged to dig deeper until I found a solution.

Below is a version that does solve the problem. I don't understand why the one version gives ticks at the end of the month and the other at the start of the month.

library(ggplot2)
library(scales)

mydata <- read.table(header = TRUE, text = "
            dates values
            2022-12-03 5
            2023-03-02 0
            ")

# This gives tick marks at the END of the month 
# plottib <- tibble(mydata) %>%
#   mutate(dates = as.POSIXct(dates, format="%Y-%m-%d"), tz="UTC" )

# This gives tick marks at START of the month
plottib <- tibble(
  dates = as.POSIXct(mydata$dates, format="%Y-%m-%d", tz="UTC" ),
  values = mydata$values)

gp <- ggplot( plottib , aes( x=dates, y=values )) +
  geom_point() +
  scale_x_datetime(date_breaks = "1 month", labels = date_format("%d %b") ) 

gp
donman
  • 57
  • 3