Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to plot data in a chronological order while showing numerical labels on the x axis in ggplot 2

I have a data frame like this:

df <- data.frame( Time = as.POSIXct(c("2023-08-01 08:00:00", "2023-08-01 12:00:00","2023-08-05 08:00:00", "2023-08-05 12:00:00","2023-08-10 08:00:00", "2023-08-10 12:00:00","2023-08-15 08:00:00", "2023-08-15 12:00:00")),  DAS = c(0, 0, 4, 4, 9, 9, 14, 14), emmean = c(10, 15, 20, 25, 30, 35, 40, 45) )

I am trying to plot my data in a chronological order (so I need the posixct format I think) while using the numerical DAS values on my x-axis.

p<-ggplot(df, aes(x = Time, y = emmean)) + geom_point()

Basically the two options that get the closest results are:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. p + scale_x_continuous(breaks = df$Time, labels = df$DAS)
  2. p + scale_x_datetime(breaks = df$Time, labels = df$DAS, date_breaks = "1 day", date_labels = "%b %d")

The problem with 1 is that I get the DAS label repeated for each timepoint, which is an issue with my data, as there are way too many points. I want one DAS value for the whole day, not per measurement.
The problem with 2 is that is still shows the date instead of the DAS values.
I would like the break frequency of option 2 with the labeling of option 1.

Is there a way to do this?

>Solution :

It looks as though DAS is the number of days since the first measurement. One option would be to have this explicitly calculated on-the-fly. Simply subtract min(Time) from Time, which will give you the number of seconds since the first measurement. Convert this to days by dividing by 86400 (the number of seconds in a day)

ggplot(df, aes(x = as.numeric(Time - min(Time))/86400, y = emmean)) + 
 geom_point() +
 xlab('DAS')

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading