1
votes

I'm trying to plot a time series. In one dataframe(y), I have 56 items in a column vector and I have a second dataframe (dates) with corresponding dates. I am trying to graph the time series as the values of y on the y-axis and the dates on the x axis. I have tried a number of things using ggplt2 geom_freqpoly but I can't figure it out. I'm open to other methods besides ggplot and i can cbind date and y into one dateframe as well if it will make things easier.

Any advice?

library(ggplot2)

set.seed(123)

N<- 500
M<-56

x<- matrix( rnorm(N*M,mean=23,sd=3), N, M)
y <- colMeans(x,dim=1)

y <-as.data.frame(y)

Date <- seq(as.Date("2018-01-01"), as.Date("2018-02-25"), by="days")
Date <- as.POSIXct(Date, format = "%Y-%m-%d %H:%M")

a <- ggplot(date, aes(y))
a + geom_freqpoly()
1

1 Answers

4
votes

Here are methods from several different packages.

ggplot2

The package works the best on a data frame, so I would suggest you to create a data frame with your data. In addition, not sure why do you want to use geom_freqpoly. I think geom_line will work for time-series data.

library(ggplot2)

set.seed(123)

N<- 500
M<-56

x<- matrix( rnorm(N*M,mean=23,sd=3), N, M)
y <- colMeans(x,dim=1)

Date <- seq(as.Date("2018-01-01"), as.Date("2018-02-25"), by="days")
Date <- as.POSIXct(Date, format = "%Y-%m-%d %H:%M")

dat <- data.frame(Date = Date, y = y)

ggplot(dat, aes(x = Date, y = y)) +
  geom_line() +
  theme_classic()

enter image description here

ggpubr

is an extension of the package. We can use ggline package to plot the data.

library(ggpubr)    
ggline(data = dat, x = "Date", y = "y")

enter image description here

lattice

We can also use the xyplot function from the package.

library(lattice)

xyplot(y ~ Date, data = dat, type = "l")

enter image description here

ggvis

The package, similar to , uses grammar of graphics to create plots.

library(ggvis)

ggvis(dat, ~Date, ~y) %>% layer_lines()

enter image description here

Base R

We can also use the base R.

plot(dat$Date, dat$y, xaxt = "n", type = "l", xlab = "Date", ylab = "y")
axis.POSIXct(1, at = seq(min(dat$Date), max(dat$Date), by = "week"), format="%b %d")

enter image description here

xts

We can also convert the data frame to an object and then plot it.

library(xts)

dat.ts <- xts(dat$y, order.by = dat$Date)
plot(dat.ts)

enter image description here

PerformanceAnalytics

We can also use the chart.TimeSeries from the package to plot the xts package.

chart.TimeSeries(dat.ts) 

enter image description here

dygraphs

The package can create interactive time-series plot.

library(dygraphs)

dygraph(dat.ts)

enter image description here

plotly

We can also use to create interactive plot.

library(plotly)

plot_ly(x = ~dat$Date, y = ~dat$y, mode = 'lines')

enter image description here

We can also use package to create interactive plot.

library(highcharter)

hchart(dat.ts)

enter image description here