I have two plots displaying supply and demand, and one plot in which I have subtracted the demand from the supply to show the resulting asymmetry. I would like to shade the area between the x-axis and the negative part of the asymmetry, to show the extent of the deficit.
I currently use the following code:
plot.asymmetry <- ggplot(data=df.overview.month,
aes(x=Date.Time, y=Asymmetry)) +
geom_area(data=subset(df.overview.month, Asymmetry < 0),
aes(x=Date.Time, y=Asymmetry))
However – as could be expected – this does not shade the area between geom_line and the x-axis, but only between negative values of the asymmetry data, which is something else entirely, as shown in the resulting graph:

Is there any way to overcome this problem?
/Edit: some example data:
time.initial <- as.POSIXct("2010-12-31 23:00:00", tz="GMT")
Date.Time<-vector()
for(i in 1:24) {
Date.Time[i] <- time.initial + i*3600
}
Demand<-vector()
for(i in 0:23) {
Demand[i+1] <- 155 + 20*sin((pi/12)*i - (pi/2)) + 10*sin((pi/4380)*i + (pi/2))
}
Supply<-vector()
for(i in 0:23) {
Supply[i+1] <- 165 + 5*sin((pi/4380)*i - (pi/2)) + rnorm(1, mean=0, sd=0.20*165)
}
df.overview.month <- data.frame(Date.Time, Demand, Supply, Asymmetry=Supply-Demand)
What about this as inspiration. Now you only need to add additional data points where the asymmetry is equal to zero (like @baptiste suggested). I create a new column which is
NAwhen the asymmetry is above zero, in this way no geom_ribbon will be drawn there. Just subsetting the data will not lead to the required plot.Some additional notes about the way you constructed your example. The most important one is that R is vectorized. For example:
is equivalent to:
In this case the reduction in code is modest, but in other (more realistic) settings using vectorization will save you dozens of lines of code.