0
          Hour  CrimeFreq       
1   1:00:00 AM  547
2   1:00:00 PM  543
3   10:00:00 AM 472
4   10:00:00 PM 735
5   11:00:00 AM 464
6   11:00:00 PM 667
7   12:00:00 AM 741
8   12:00:00 PM 629
9   2:00:00 AM  601
10  2:00:00 PM  577
11  3:00:00 AM  383
12  3:00:00 PM  570
13  4:00:00 AM  215
14  4:00:00 PM  611
15  5:00:00 AM  159
16  5:00:00 PM  703
17  6:00:00 AM  189
18  6:00:00 PM  671
19  7:00:00 AM  235
20  7:00:00 PM  646
21  8:00:00 AM  349
22  8:00:00 PM  589
23  9:00:00 AM  422
24  9:00:00 PM  684

I have the data above (aggregated from a larger data set) I plotted a line graph using ggplot

ggplot(Time.Assault2014, aes(x=Hour, y= CrimeFreq, group=1)) + geom_line()

The graph comes out like this:

enter image description here

Is there a way I can order the x-axis to go from 12AM to 11PM? I want to show how CrimeFreq changes throughout the day.

Basically I want it to look like this (from tableau)

enter image description here

neilfws
  • 32,751
  • 5
  • 50
  • 63
NVerde
  • 3
  • 1

1 Answers1

0
library(dplyr)

df2 <- df %>% 
    mutate(time = strptime(Hour, format="%I:%M:%S %p") %>% format(., "%H"))

ggplot(df2, aes(time, CrimeFreq, group=1)) + 
       geom_line()

enter image description here

EDIT: Added more robust time-coding and scale_x_datetime to replicate the tableau graph.

df2 <- df %>% 
      mutate(time = as.POSIXct(strptime(Hour, format="%I:%M:%S %p", tz="Singapore")))

ggplot(df2, aes(time, CrimeFreq, group=1)) + geom_line() +
   scale_x_datetime(date_breaks = "2 hour",
                    labels = function(x) format(x, format = "%I%p", tz="Singapore"))

enter image description here

Adam Quek
  • 6,973
  • 1
  • 17
  • 23
  • Thanks! I found a way to rename the x-axis tick marks so it looks like the one in tableau, thanks a bunch! – NVerde Oct 20 '17 at 05:36
  • @NVerde edited the code above for slightly more robust time-coding in ggplot. Timezone could be a bitch though. – Adam Quek Oct 20 '17 at 08:58