1

firstly May you have a good day when Christmas.

I ecounter a question at the aspect of Date display when using ggplot2.

theme_set(theme_bw())
datebreaks <-  seq(as.Date('2012-01-01'), as.Date('2012-12-01'), by = '1 month')

p <- scale_x_date(breaks = datebreaks, date_labels = 
                    '%b %d')

df %>% filter(YEAR == '2012') %>% 
  ggplot(aes(as.Date(DATE),VALUE)) + geom_line()  + p 
  

It will get the picture as below:

enter image description here

But I want to get the pic as below:

enter image description here

You can see the arrow direct to the position where I want to mark one axis tick but no any label here. I don't know how to cope with it . Could you tell me the code, please?

Thanks in advance.

Here is my test dataset. dput() generates code as below:

df <- structure(list(DATE = structure(c(15458, 15459, 15460, 15461, 
15462, 15463, 15464, 15465, 15466, 15467, 15468, 15469, 15470, 
15471, 15472, 15473, 15474, 15475, 15476, 15477, 15478, 15479, 
15480, 15481, 15482, 15483, 15484, 15485, 15486, 15487, 15488, 
15489, 15490, 15491, 15492), class = "Date"), YEAR = structure(c(10L, 
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L), .Label = c("2003", "2004", 
"2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", 
"2013", "2014", "2015", "2016", "2017", "2018"), class = "factor"), 
    VALUE = c(NA, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 33, 0, 0, 
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 185, 0, 0, 3, 50, 0, 8, 0, 
    2, 0)), row.names = c(NA, -35L), class = c("tbl_df", "tbl", 
"data.frame"))

MrFlick
  • 195,160
  • 17
  • 277
  • 295
PeterPanPan
  • 151
  • 4
  • On what date do you want that axis tick mark to appear? – MrFlick Dec 21 '20 at 08:16
  • This might be helpful: https://stackoverflow.com/questions/34533472/insert-blanks-into-a-vector-for-e-g-minor-tick-labels-in-r/34533473#34533473 – MrFlick Dec 21 '20 at 08:18

1 Answers1

0

You can set the breaks to whatever you like, and use a custom labeller function to write blanks if the date doesn't fall on the first of the month:

library(ggplot2)
library(dplyr)

datebreaks <- as.Date(c("2012-05-01", "2012-05-15", "2012-06-01"))

df %>% 
  filter(YEAR == '2012') %>% 
  ggplot(aes(as.Date(DATE),VALUE)) + 
  geom_line() + 
  scale_x_date(breaks = datebreaks, 
                  labels = function(x) ifelse(substr(x, 10, 10) == 1,
                             format(x,'%b %d'), "")) +
  theme_bw()
#> Warning: Removed 1 row(s) containing missing values (geom_path).

Created on 2020-12-21 by the reprex package (v0.3.0)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87