How to plot several different line-cum-point curves based on different parameter values in a formula?
I want to plot a simple formula, say one for compound interest. The x-axis should have years and the y -axis should have final amount. There should be several curves, one for each interest rate on the same set of axes. I am getting just one column containing ALL the values and not several columns, one for each value of the rate.
r <- c(0,.05,.08,.1,.15) # Interest rates
C <- 100 # Initial amount
t <- seq(0, 20, by = 1) # Say, 20 years investment
fv <- C*(1+r)^t
df <- data.frame(cbind(t,fv)) # creates the data frame but with only 2 columns.
ggplot(df)+ # will obviously not plot several curves
geom_point(aes(x = t, y = FV), size = 3)+
geom_line() # I need a line for each r value
xlab("Number of years")+
ylab(paste("Future value of Rupees",C))
Will using the above vectorized approach work? Or do I need a for loop for this?
You can try building the data frame with dplyr
and map r
to the color
aesthetic in ggplot
library(tidyverse)
df <- data.frame(
r = sort(rep(c(0,.05,.08,.1,.15), 21)),
t = rep(seq(0, 20, by = 1), 5)
)
df %>%
dplyr::mutate(fv = 100 * (1 + r)^t) %>%
ggplot(aes(x = t, y = fv, color = r)) +
geom_point(size = 3) +
xlab("Number of years")+
ylab(paste("Future value of Rupees", 100))
Created on 2019-10-13 by the reprex package (v0.3.0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.