R: Creating a ggplot2 barchart of timedate y-variable -
i'm having lot of trouble trying create otherwise simple ggplot barchart of timedate variable on y-axis. plots fine using geom_point
or geom_line
, replace geom_bar
, r either crashes or returns me blank, grey graph.
my raw data character strings of format:
day time 1/1/2015 2:30:14 2/1/2015 15:10:40 3/1/2015 8:50:05
and knowing ggplot2 can bit picky time , date classes, format variables posixct , date follows:
library(ggplot2); library(scales) datetime <- data.frame(date = c("1/1/2015", "2/1/2015", "3/1/2015"), time = c("2:30:14", "15:10:40", "8:50:05")) datetime$date <- as.date(datetime$date, format="%m/%d/%y") datetime$time <- as.posixct(datetime$time, format="%h:%m:%s")
then, creating simple scatter plot of data works fine:
ggplot(datetime, aes(date, time)) + geom_point() + xlab("day") + ylab("time") + scale_y_datetime(breaks = date_breaks("1 hour"), labels = date_format("%h:%m"))
but, replacing geom_point()
geom_bar(stat="identity")
create barchart seems result in everloading process , crashing of r:
ggplot(datetime, aes(date, time)) + geom_bar(stat="identity") + xlab("day") + ylab("time") + scale_y_datetime(breaks = date_breaks("1 hour"), labels = date_format("%h:%m"))
i'm misunderstanding functionality of ggplot2, can please enlighten me going on here?
in ggplot2 barchart's y-scale default starts zero. or, in case of date , time value, start value, 1/1/1970. means bars 45-years long (for time values r apparently sets today date). force ggplot2 use fine scale on period of time: set breaks 1 hour:
scale_y_datetime(breaks = date_breaks("1 hour"), labels = date_format("%h:%m"))
which cause r crash. if use just
ggplot(data, aes(day, time)) + geom_bar(stat = "identity")
it work, bars indistinguishable. make bars distinguishable have change y-limits, example time period between 0:00:00 23:59:59. works me:
ggplot(data, aes(day, time)) + geom_bar(stat = "identity") + xlab("day") + ylab("time") + coord_cartesian(ylim=c(as.posixct("0:0:0", format="%h:%m:%s"), as.posixct("23:59:59", format="%h:%m:%s"))) + scale_y_datetime(breaks = date_breaks("1 hour"), labels = date_format("%h:%m")) + scale_x_date(breaks = pretty_breaks(10))
Comments
Post a Comment