[R] Date order question

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Wed Jan 4 23:36:39 CET 2023


Às 21:08 de 04/01/2023, Thomas Subia escreveu:
> Colleagues,
> 
> date<-c("12-29","12-30","01-01")
> PT <- c(.106,.130,.121)
> data <- data.frame(date,PT)
> ggplot(data, aes(x=date,y=PT,group=1))+
>    geom_point(size=4)+
>    geom_line()+
>    geom_hline(yintercept =c(1,.60,0,.30,.25,.2))+
>    scale_y_continuous(label=scales::label_percent(),breaks=c(1,0.6,0,.3,0.25,0.2))+
>    annotate("text", x=2.5, y=.1, label="Very Good",size=5,fontface="bold")+
>    annotate("text", x=2.5, y=.225, label="Good",size=5,fontface="bold")+
>    annotate("text", x=2.5, y=.28, label="Marginal",size=5,fontface="bold") +
>    annotate("text", x=2.5, y=.45, label="Inadequate",size=6,fontface="bold")+
>    annotate("text", x=2.5, y=.8, label="OOC",size=6,fontface="bold")+
>    annotate("text", x=2.5, y=-.05, label="PT Not Done",size=5,fontface="bold")+
>    theme_cowplot()
> 
> The plot has the wrong date order.
> What is desired is 12-29, 12-30 and 01-01.
> 
> Some feedback would be appreciated.
> 
> All the best,
> Thomas Subia
> 
> "De quoi devenir chevre? Des donnees"
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Hello,

Transform `date` into a real date column in a dplyr pipe so that the 
original data remains unchanged and plot with scale_x_date which will 
allow for control over the axis breaks and labels.

The only problem are now the text annotations. The x coordinate is 
numeric and it must also be a date object. Below I solve this by 
creating a annotations data set ann_data. In geom_text the data argument 
is now another one, but one layer only annotates all areas.


library(ggplot2)
library(cowplot)
library(dplyr)

date<-c("12-29","12-30","01-01")
PT <- c(.106,.130,.121)
data <- data.frame(date,PT)

ann_data <- data.frame(
   y = c(0.1, 0.225, 0.28, 0.45, 0.8, -0.05),
   text = c("Very Good", "Good", "Marginal", "Inadequate", "OOC", "PT 
Not Done")
)
ann_data$x <- as.Date("2022-12-31")


data %>%
   mutate(newyear = ifelse(substr(date, 1, 2) > "01", "2022-", "2023-"),
          date = as.Date(paste0(newyear, date))) %>%
   ggplot(aes(x = date, y = PT)) +
   geom_point(size = 4) +
   geom_line() +
   geom_hline(yintercept = c(1,.60,0,.30,.25,.2)) +
   #
   geom_text(
     data = ann_data,
     mapping = aes(x = x, y = y, label = text),
     size = 5, fontface = "bold"
   ) +
   scale_x_date(date_breaks = "1 day", date_labels = "%m-%d") +
   #
 
scale_y_continuous(label=scales::label_percent(),breaks=c(1,0.6,0,.3,0.25,0.2))+
   theme_cowplot()



Hope this helps,

Rui Barradas



More information about the R-help mailing list