Wednesday, 7 August 2013

Rotated x labels in R

Rotated x labels in R

I have a data in R like the following:
bag_id location_type event_ts
1 155 transfer 2012-01-02 15:57:54
2 155 sorter 2012-01-02 17:06:05
3 305 arrival 2012-01-01 07:20:16
4 692 arrival 2012-03-29 09:47:52
10 748 transfer 2012-01-08 17:26:02
11 748 sorter 2012-01-08 17:30:02
12 993 arrival 2012-01-23 08:58:54
13 1019 arrival 2012-01-09 07:17:02
14 1019 sorter 2012-01-09 07:33:15
15 1154 transfer 2012-01-12 21:07:50
where class(event_ts) is "POSIXct".
I wanted to find the density of bags at each location in different times.
So, I used the function density like the following:
adj<-.00001
dSorter<-density(as.numeric(Data$event_ts[which(Data$location_type=="sorter")]),n=length(Data$event_ts[which(Data$location_type=="sorter")]),adjust
= adj)
StartTime<-as.POSIXct(strptime("2012-06-01", "%Y-%m-%d"), tz="UTC") #
want to zoom & see part of data
EndTime<-as.POSIXct(strptime("2012-06-3", "%Y-%m-%d"), tz="UTC")
Range<-range(as.numeric(c(StartTime,EndTime)))
lablist.x<-substr(seq(StartTime,EndTime,by="hour"),start=6, stop=13) #
want to have time labels for my plot
plot(dSorter, main="Sorter",xlim=Range, xaxt = "n")
axis(1, at=as.numeric(seq(StartTime,EndTime,by="hour")), labels =F)
text(1:49,par("usr")[3] - 0.25, labels=lablist.x,srt = 45,adj=1, , xpd =
TRUE) #want to rotate the labels
The last comment does not work and I do not know how should I recognize
the "x" values at function "text".
Besides, I used the function "approxfun" to add the density values to my
dataset
ApproximatePointDensitySorter<-approxfun(x=dSorter$x ,y=dSorter$y)
Data$DensityBags[which(Data$location_type=="sorter")]<-ApproximatePointDensitySorter(as.numeric(Data$event_ts[which(Data$location_type=="sorter")]))
When I use the library ggplot2, I can have a nicer plot but I do not know
how to add these densities to my data with ggplot2. (It seems that density
function and geom_density have different bandwith and methods and so on,
isn't it right?) This is my code in ggplot2
Range<-as.POSIXct(strptime(c("2012-06-01","2012-06-3"), "%Y-%m-%d"),
tz="UTC")
library(ggplot2)
library(grid)
plot1<-ggplot(Data[which(Data$location_type=="sorter"),], aes(x =
event_ts)) + geom_density(adjust = adj) + labs(title = "Sorter") +
xlim(Range)
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 2)))
vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
print(plot1, vp = vplayout(1, 1))
Thank you in advance for any kind of comments and guidance.
Best, Shima.

No comments:

Post a Comment