Ivan Bacher
Ivan Bacher

Reputation: 6154

Use scale_y_time to convert MS to Minutes and Seconds in Boxplot (GGPLOT)

I have a dateframe like below, where the column time is in milliseconds

id | group | time
1    |   A   | 1400003
2    |   B   | 1604203
3    |   A   | 170203

I am creating a boxplot ussing GGplot

ggplot(df, aes(x=group, y=time, fill=group)) + 
  geom_boxplot()

enter image description here

How can I use scale_y_datetime() or scale_y_time() convert the tick marks of the Y axis to the following format M:S?

Upvotes: 4

Views: 2431

Answers (2)

GGamba
GGamba

Reputation: 13680

We can convert the time values to a difftime object (in seconds) and then format the y axis labels:

df <- read.table(text = 'id | group | time
1    |   A   | 1400003
2    |   B   | 1604203
3    |   A   | 170203', sep = '|', header = TRUE)

df$time <- as.difftime(df$time/1000, units = 'secs')

library(ggplot2)
ggplot(df, aes(x=group, y=time, fill=group)) + 
  geom_boxplot() +
  scale_y_time(labels = function(l) strftime(l, '%M:%S'))

Created on 2018-05-04 by the reprex package (v0.2.0).

Upvotes: 5

Prem
Prem

Reputation: 11955

How about this?

library(ggplot2)
library(scales)

#choose correct 'origin' as per your data
ggplot(df, aes(x=group, y=as.POSIXct(time, origin="1970-01-01", tz="GMT"), fill=group)) + 
  geom_boxplot() +
  scale_y_datetime(breaks = date_breaks("24 hours"),
                   labels = date_format("%b %d, %Y\n%H:%M:%S")) +
  ylab("Time")

Sample data:

df <- structure(list(id = c(1, 2, 3), group = c("A", "B", 
"A"), time = c(1400003L, 1604203L, 170203L)), .Names = c("id", 
"group", "time"), class = "data.frame", row.names = c(NA, -3L
))

Upvotes: 2

Related Questions