Question

I have table of data that I am attempting to use lattice in R to graph. The table contains counts of a certain event that occurs per unit by date (which I have grouped by the first day of the corresponding month), sorted by date.

> data
      Unit       Date Count
1   Unit14 2005-01-01     1
2   Unit19 2005-01-01     0
3   Unit13 2006-01-01     8
4   Unit17 2006-01-01     0
5   Unit13 2007-01-01     0
6   Unit14 2007-01-01     4
7   Unit19 2007-01-01     1
8    Unit5 2007-01-01     0
9    Unit9 2007-01-01     1
10  Unit13 2008-01-01     0
...

I am using xyplot in lattice to plot, and it works fine if I am just plotting the points at which they occurred. I get a grid of images by Unit plotting each event with x-axis as Date, and y-axis as Dount.

> xyplot(Count~Date | Unit, data)

But, when I try to plot it as a line graph it does not understand that the order of events were by time of event, and the line doubles back on itself. In other words, the line starts in the middle of the graphs and makes "star" like patterns between the points.

> xyplot(Count~Date | Unit, data, col="blue",type="l")

How can I get this to plot as time series?

I'm still pretty new to graphing with R, so any help will be greatly appreciated. Thank you.

Was it helpful?

Solution

The points are drawn and joined in the order in which they appear, not in chronological order. Those artefacts will disappear if you sort your data.frame before plotting.

# Sample data
n <- 20
k <- 3
d <- data.frame(
  Unit = rep(LETTERS[1:k], each=n),
  Date = rep(sample(seq.Date(Sys.Date(), length=n, by=1)), k),
  Count = rpois(k*n,10)
)
# Unorderd data    
xyplot(Count ~ Date | Unit, data=d, type="l")
# Ordered data
xyplot(Count ~ Date | Unit, data=d[order(d$Date),], type="l")

Note that this does not happen with ggplot2 (unless your explicitly ask for that "star-shape" artefact):

library(ggplot2)
ggplot(d, aes(Date, Count)) + geom_line() + facet_grid(~Unit)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top