Reputation: 2282
I have some time series data with gaps.
df<-read.table(header=T,sep=";", text="Date;x1;x2
2014-01-10;2;5
2014-01-11;4;7
2014-01-20;8;9
2014-01-21;10;15
")
df$Date <- strptime(df$Date,"%Y-%m-%d")
df.long <- reshape::melt(df,id="Date")
ggplot(df.long, aes(x = Date, y = value, fill = variable, order=desc(variable))) +
geom_area(position = 'stack')
Now ggplot fills in the missing dates (12th, 13th, ...). What I want is just ggplot to not interpolate the missing dates and just draw the data available. I've tried filling NA with merge for the missing dates, which results in an error message of removed rows.
Is this possible? Thanks.
Upvotes: 3
Views: 3956
Reputation: 81693
You can add an additional variable, group
, to your data frame indicating whether the difference between two dates is not equal to one day:
df.long$group <- c(0, cumsum(diff(df.long$Date) != 1))
ggplot(df.long, aes(x = Date, y = value, fill = variable,
order=desc(variable))) +
geom_area(position = 'stack', aes(group = group))
Update:
In order to remove the space between the groups, I recommend facetting:
library(plyr)
df.long2 <- ddply(df.long, .(variable), mutate,
group = c(0, cumsum(diff(Date) > 1)))
ggplot(df.long2, aes(x = Date, y = value, fill = variable,
order=desc(variable))) +
geom_area(position = 'stack',) +
facet_wrap( ~ group, scales = "free_x")
Upvotes: 4