0

I have data of dates that is in the morning and in the afternoon. I want to create a geom_bar that divides the dates into AM and PM. Right now my function has the geom_bar overlapping. My graphing function looks like this:

ggplot(DF, aes(x = DATE, y = value)) + geom_bar(position = "dodge", stat = "identity") +
  + scale_fill_manual(values=unique(DF$DATE))

DF also has the property dt (stands for datetime), which has the year,month,day,hour,min,sec.

DATE is just the year-month-day part of the date.

If I put x = dt inside aes instead of x = DATE , I will get very skinny geom_bars. How can I divide the x_axis into half days and dt into half days so that I have 2 large geom_bars that spans each date?

ilovedata17
  • 25
  • 1
  • 4
  • 1
    Do you have times? If so you could do this with a pretty straightforward conversion to `as.POSIXct("2014-04-06 16:30") > 12`. Show us your data or make an example! http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Brandon Bertelsen Jul 25 '14 at 20:57

1 Answers1

0

Here's some sample data I made up based on your description

DF<-data.frame(
    dt=as.POSIXct(runif(500,as.numeric(as.POSIXct("2012-01-01")),
        as.POSIXct(as.Date("2012-01-31"))), 
        origin="1970-01-01", tz="GMT"),
    value = rnorm(500, 100, 6)
)
DF<-transform(DF, DATE=as.Date(dt))

Now, to get half-day values, i'll actually just do some atrithmatic on the values since they are stored as seconds since a sentinel date.

DF<-transform(DF, HALFDAY=dt -(as.numeric(dt) %% (60*60*12)))
DF<-transform(DF, PART=ifelse(as.numeric(HALFDAY) %% (60*60*24) > 0,"PM","AM"))

Basically I just truncate each date/time to a 12 hour period. It's important to do these transformations in GMT time so you don't have to worry about local time variations. Also with DATE it would be bad to do position=dodge because you're not really grouping by anything. This would just plot the values in front of each other which is likely not what you want should you have multiple observations for day. You really want to stack those. So here are the three different plots from this data

ggplot(DF, aes(x = dt, y = value)) + 
    geom_bar(position="dodge", stat = "identity", width=60*60*2) +
    ggtitle("dt")

ggplot(DF, aes(x = DATE, y = value)) + 
    geom_bar(position="stack", stat = "identity") +
    ggtitle("DATE")

ggplot(DF, aes(x = HALFDAY, y = value, fill=PART)) + 
    geom_bar(position="stack", stat = "identity") +
    ggtitle("HALFDAY")

which gives

enter image description here

of course you don't have to color the half days by AM/PM but I liked it.

MrFlick
  • 195,160
  • 17
  • 277
  • 295