Fung Kwong Kit
Fung Kwong Kit

Reputation: 21

Plotting hourly time series with unspecified time

I am currently working on a dataframe with 25 columns and 120 rows. As in the dataframe, date and time are stored separately. An extract of my dataframe is like this:

          date 1 2 3 4 5 6   7    8    9   10   11   12
1   2013-08-01 0 0 0 0 0 0 369 2416 1934 1125  768  653
2   2013-08-02 0 0 0 0 0 0 401 2328 1962 1080  849  588
5   2013-08-05 0 0 0 0 0 0 551 2855 2317 1099  876  805
6   2013-08-06 0 0 0 0 0 0 420 2382 1937 1065  844  710
7   2013-08-07 0 0 0 0 0 0 405 2397 1930 1081  768  773
8   2013-08-08 0 0 0 0 0 0 391 2273 1942 1098  831  633
11  2013-08-12 0 0 0 0 0 0 555 2938 2163 1071  898  700
12  2013-08-13 0 0 0 0 0 0 323 2375 1819 1087  905  734

where only 12 hours out of 24 hours are shown.

I want to have an hourly time series plot with minimal changes to the above dataframe. Thanks in advance.

Upvotes: 0

Views: 86

Answers (2)

AdagioMolto
AdagioMolto

Reputation: 192

You have to melt the data.frame to make the hour a single variable, as you want to look at it as a single variable.

library(data.table)
hour_cols <- as.character(1:24)
plot_df <-
  melt(your_data_frame, id.vars = "date", measure.vars = hour_cols)
require(ggplot2)
ggplot(plot_df, aes(x = variable, y = value, colour = date)) +
  geom_point()

See ?data.table::melt for further details on this method.

EDIT: This method will of course will only look good with not too many different dates. I here considered that there will only be the 12 dates you supplied in the question.

Upvotes: 1

m0nhawk
m0nhawk

Reputation: 24148

You need to convert you date from wide to long format. For this you can use gather from tidyr (?tidyr::gather) and combine date and time:

library(tidyr)
long_data <- data %>%
  gather(time, val, `1`:`12`) %>%
  mutate(datetime = paste0(date, " ", time, ":00"))

And then plot the data:

library(ggplot2)
ggplot(long_data, aes(x = variable, y = value) +
  geom_point()

Upvotes: 0

Related Questions