Huachen Qin Huachen Qin - 12 days ago 5
R Question

R Plot Histogram On Dataframe with dates-time object

I have the following R dataframe with column Date and column Value, column Date is R chron objects (format <- "m/d/y h:m:s").

What I want to do is to visualize the time series data by ploting histogram or line chart, and I also want to specify the date-time range on x-axis (e.g. from 10/2/16 20:00:00 to 10/3/16 20:00:00). However after searching for the online guides I still do not have a clue.

Would anyone give me a sample code using ggplot or other package? I appreciate your help.

Date Value
(10/03/16 09:31:00) 180,912.00
(10/03/16 09:32:00) 112,359.00
(10/03/16 09:35:00) 93,539.00
(10/03/16 09:35:00) 156,283.00
(10/03/16 09:36:00) 226,704.00
(10/03/16 09:37:00) 780,094.00
(10/03/16 09:45:00) 184,632.00
(10/03/16 09:48:00) 144,984.00
(10/03/16 09:49:00) 311,035.00
(10/03/16 09:51:00) 210,653.00
(10/03/16 09:51:00) 72,626.00
(10/03/16 09:52:00) 241,173.00
(10/03/16 09:54:00) 233,416.00
(10/03/16 09:55:00) 146,550.00
(10/03/16 10:24:00) 331,191.00
(10/03/16 10:28:00) 107,015.00
(10/03/16 10:36:00) 196,162.00
(10/03/16 10:41:00) 466,879.00
(10/03/16 10:44:00) 294,589.00
(10/03/16 10:48:00) 164,339.00
(10/03/16 10:52:00) 137,082.00
(10/03/16 10:58:00) 180,667.00
(10/03/16 11:04:00) 259,475.00





Updated on 11/28/2016 6:35 pm
With the help of yeedle's codes, I am able to plot the following:


ggplot(temp_merge_sub1, aes(x=Date, y=Value,
group=1)) + geom_bar(stat = "identity")


GGPlot2

What I really want to improve from that is:


  • how to correctly set the breaks on y-axis?

  • how to set breaks on x-axis and display the histogram on the added up value in each of the 2-hour intervals?



Thank you for your help! I appreciate it!

Answer

I converted Date to POSIXct objects, using lubridate's ymd_hms function.

library(ggplot2)
ggplot(df, aes(x=Date, y=Value)) + 
  geom_bar(stat="identity") + 
  scale_x_datetime(limits =c(mdy_hms("10/2/16 20:00:00"),mdy_hms("10/3/16 20:00:00")))

bar plot with 1-day scale

You get a clearer picture without the scale_x_datetime limits:

bar plot with no scale limits

Simply replace geom_bar with geom_line for a line graph:

ggplot(df, aes(x=Date, y=Value)) + 
  geom_line()

line plot