Graphics Reference
In-Depth Information
Using Relative Times on an Axis
Problem
You want to use relative times on an axis.
Solution
Times are commonly stored as numbers. For example, the time of day can be stored as a number
representing the hour. Time can also be stored as a number representing the number of minutes
or seconds from some starting time. In these cases, you map a value to the x- or y-axis and use
a formatter to generate the appropriate axis labels ( Figure 8-40 ):
# Convert WWWusage time-series object to data frame
www <- data.frame(minute = as.numeric(time(WWWusage)),
users = as.numeric(WWWusage))
# Define a formatter function - converts time in minutes to a string
timeHM_formatter <- function
function (x) {
h <- floor(x / 60 )
m <- floor(x %% 60 )
lab <- sprintf( "%d:%02d" , h, m) # Format the strings as HH:MM
return
return (lab)
}
# Default x axis
ggplot(www, aes(x = minute, y = users)) + geom_line()
# With formatted times
ggplot(www, aes(x = minute, y = users)) + geom_line() +
scale_x_continuous(name = "time" , breaks = seq( 0 , 100 , by = 10 ),
labels = timeHM_formatter)
Search WWH ::




Custom Search