Thaqor
Thaqor

Reputation: 49

R facet_wrap not showing facet that has different numbers of observations

I am trying to plot a set of time-series data where some data are observed quarterly and others are observed monthly. When I plot my data, however, the facet containing the data that has fewer observations doesn't come out correctly.

In my actual data set, I'm getting a bit of a different outcome, but I think that the problem I face in the example below is probably due to the same underlying problem. You'll see in the example below, that the last facet doesn't display a line at all. In my actual dataset, the last facet displays all of the points, but they are compressed together at the start of the graph as if the observations were happening monthly. So the line in the last facet is a quarter the length of frame, which spans the whole time period.

a <- economics[1:100,]
a[seq(1,100,2), "unemploy"] <- NA
b <- melt(a,id.vars="date")
smPlot  <- ggplot(b, aes_string(x="date", y="value")) +
  geom_line() +
  facet_wrap(~ variable, ncol=5, scales="free")
smPlot  

Which creates the following plot:

enter image description here

Upvotes: 1

Views: 2707

Answers (1)

dww
dww

Reputation: 31452

The issue in your example code is that a line must have at least 2 points. If every other point is NA (as in the last facet), each line segment has only one point in it so does not show anything.

To expand on this a little, consider how a line trace is drawn. It is comprised of many line segments, each having a start and an end. In continuous data that does not have any NA's, then each segment starts where the last ended. But when there is an NA in the data, it will break the line and a new line starts from the next non-NA data point. So when there is only a single data point between each NA, each segment has only a single point and cannot be drawn as a line (but could be shown as a point using geom_point).

If you just subset out the rows with NA, it should look fine

smPlot  <- ggplot(b[!is.na(b$value), ], aes_string(x="date", y="value")) +
  geom_line() +
  facet_wrap(~ variable, ncol=5, scales="free")
smPlot  

enter image description here

Upvotes: 2

Related Questions