I am coloring an area between a line as shown in the graph here.
However, the shaded area exceeds in some places the line as well as the x-axis.
What is the best way to define the geom_area
only to the specific areas under/ above the line?
Here is the code to generate the graph:
library(dplyr)
library(ggplot2)
library(quantmod)
data.start.date <- "1990-01-01"
#temporary fix for FRED address change [only needed on MAC computers]
# options(download.file.method="libcurl")
# get symbols from FRED and convert to data frame
var.list <- c("IR", "IQ")
getSymbols(var.list, src="FRED")
ir.df <- data.frame(date= index(IR),IR$IR)
iq.df <- data.frame(date= index(IQ),IQ$IQ)
df <- dplyr::left_join(ir.df, iq.df, by = "date")
# Shorten dataframe, starting as defined above
df = dplyr::filter(df, date >= data.start.date)
# calculate trade balance (exports-imports)
df$tradebal <- df$IQ-df$IR
ggplot(data = df)+
geom_line(aes(x=date, y=tradebal, color="Trade Balance"),size=1.2) +
geom_area(aes(x=date, y=tradebal, fill=tradebal>0), alpha=.4)