I have a data frame that contains the yield of bonds of different durations at different point in time.
For example, my dataframe would look like that
bond_duration <- c("three_mth", "one_yr", "two_yr", "five_yr", "seven_yr", "ten_yr")
Jan_2007 <- c(3.12, 2.98, 3.01, 3.07, 3.11, 3.18)
Feb_2007 <- c(2.93, 2.89, 2.91, 2.99, 3.02, 3.08)
Mar_2007 <- c(2.62, 2.53, 2.51, 2.70, 2.79, 2.91)
df <- as.data.frame(cbind(bond_duration, Jan_2007, Feb_2007, Mar_2007))
df[, 2:4] <- apply(df[, 2:4], 2, as.numeric)
The first column contains bonds with different durations. In the next three columns (columns 2 to 4), it shows the yield of each bond at that particular point in time (e.g. January 2007).
What I want to achieve is to use the Apply function to create multiple line graph from the data found within each time point (e.g. line graph of the yield of all bond duration for January 2007, line graph of the yield of all bond duration for February 2007, etc).
My x-axis will be the different bond durations while my y-axis will be the yield.
I can individually plot the yield curve for each time point with success with the following code:
ggplot(data, aes(x = bond_duration, y = Jan_2007, group = 1)) + geom_point() + geom_line() +
scale_x_discrete(limits = c("three_mth", "one_yr", "two_yr", "five_yr", "seven_yr",
"ten_yr")) +
ggtitle(paste(colnames(data)[2], " Yield Curve", sep = "")) +ylab("Yield (%)")
However, when I attempt to use the Apply function to loop the creation of multiple line graphs for each time point, my script works. The script is able to create multiple line graphs for each time point, however the title for each line graph is the same. I used the following code:
apply(data, 2, function(x) ggplot(data, aes(x = bond_duration, y = x, group = 1)) + geom_point() + geom_line() +
scale_x_discrete(limits = c("three_mth", "one_yr", "two_yr", "five_yr", "seven_yr",
"ten_yr")) +
ggtitle(paste(colnames(data)[x], " Yield Curve", sep = "")) + ylab("Yield (%)"))
I suspect something is wrong with the ggtitle section of my code. I want each line graph to be named (particular_timepoint)_yield curve.
Any help is appreciated. Thanks!