Moving x or y axis together with tick labels to the middle of a single ggplot (no facets)

后端 未结 4 1056
不思量自难忘°
不思量自难忘° 2020-12-03 06:35

I made the following plot in Excel:

But then I thought I would make it prettier by using ggplot. I got this far:

If you\'re curious, the da

4条回答
  •  无人及你
    2020-12-03 06:41

    As alistaire commented it can be done using geom_hline and geom_text as shown below.

    df <- data.frame(YearMonth = c(200606,200606,200608,200701,200703,200605),
                 person1 = c('Alice','Bob','Alice','Alice','Bob','Alice'),
                 person2 = c('Bob','Alice','Bob','Bob','Alice','Bob'),
                 Event = c('event1','event2','event3','event3','event2','event4')
    )
    
    df$YM <- as.Date(paste0("01",df$YearMonth), format="%d%Y%m")
    rangeYM <- range(df$YM)
    
    ggplot()+geom_blank(aes(x= rangeYM, y = c(-1,1))) + labs(x = "", y = "") +
    theme(axis.ticks = element_blank()) +
    geom_hline(yintercept = 0, col = 'maroon') +
    scale_x_date(date_labels = '%b-%y', date_breaks = "month", minor_breaks = NULL) +
    scale_y_continuous(minor_breaks = NULL) +
    geom_text(aes(x = df$YM, y = 0, label = paste(format(df$YM, "%b-%y")), vjust = 1.5), colour = "#5B7FA3", size = 3.5, fontface = "bold") 
    

提交回复
热议问题