Reputation: 2183
I have a dataframe df
time value
1 08:04 0
2 08:12 0
3 08:20 60
4 08:28 0
5 08:36 0
6 08:44 0
7 08:52 0
8 09:00 0
9 09:08 0
10 09:16 0
11 09:24 0
12 09:32 0
13 09:40 0
14 09:48 0
15 09:56 0
16 10:04 100
17 10:12 49
18 10:20 49
19 10:28 49
20 10:36 0
21 10:44 0
22 10:52 0
23 11:00 0
24 11:08 0
25 11:16 0
26 11:24 0
27 11:32 0
28 11:40 0
29 11:48 0
30 11:56 0
31 12:04 0
32 12:12 0
33 12:20 0
34 12:28 0
35 12:36 0
36 12:44 0
37 12:52 0
38 13:00 0
39 13:08 0
40 13:16 0
41 13:24 0
42 13:32 0
43 13:40 0
44 13:48 0
45 13:56 0
46 14:04 0
47 14:12 0
48 14:20 0
49 14:28 0
50 14:36 91
51 14:44 44
52 14:52 43
53 15:00 43
54 15:08 0
55 15:16 0
56 15:24 0
57 15:32 0
58 15:40 0
59 15:48 42
60 15:56 41
61 16:04 41
62 16:12 41
63 16:20 41
64 16:28 42
65 16:36 42
66 16:44 42
67 16:52 42
68 17:00 42
69 17:08 42
70 17:16 42
71 17:24 42
72 17:32 41
73 17:40 41
74 17:48 41
75 17:56 41
76 18:04 40
77 18:12 40
78 18:20 40
79 18:28 39
80 18:36 39
81 18:44 37
82 18:52 37
83 19:00 37
84 19:08 37
85 19:16 37
86 19:24 33
87 19:32 33
88 19:40 33
89 19:48 34
90 19:56 34
91 20:04 34
92 20:12 50
93 20:20 67
94 20:28 36
95 20:36 36
96 20:44 36
97 20:52 36
98 21:00 36
99 21:08 37
100 21:16 39
101 21:24 41
102 21:32 42
103 21:40 44
104 21:48 46
105 21:56 47
In the above, df$time
is a string and df$value
is an integer.
I'd like to plot it with time as the x-axis, and for each hour to be marked. How do I do that?
So far I've guessed seq(df$time[1], df$time[length(df$time)], by = "hour")
but this returns an error.
Upvotes: 0
Views: 5421
Reputation: 10352
My Base R and lubridate
solution:
library(lubridate)
h <- hour(hm(df$time))
plot(h, df$value)
lubridates function hm()
converts the strings in df$time
in hours and minutes and function h()
extracts the hours.
Upvotes: 1
Reputation: 132576
Base R does not support time variables for good reasons, e.g., pesky quirks like DST. You need to create a datetime variable.
df$datetime <- as.POSIXct(paste0("2016-09-23 ", df$time), tz = "GMT")
library(ggplot2)
ggplot(df, aes(x = datetime, y = value)) +
geom_point() +
scale_x_datetime(date_labels = "%H:%M", date_breaks = "1 hour")
Upvotes: 6