[英]ggplot2: Plot of function with different lines for each parameter value
plot 如何在一個公式中根據不同的參數值生成幾條不同的線兼點曲線?
我想 plot 一個簡單的公式,說一個復利。 x 軸應該有年份,y 軸應該有最終金額。 應該有幾條曲線,一條對應於同一組軸上的每個利率。 我只得到一列包含所有值而不是幾列,一個用於每個速率值。
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))
使用上述矢量化方法會起作用嗎? 或者我需要一個for循環嗎?
您可以嘗試使用dplyr
和 map r
構建數據框到ggplot
中的color
美學
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))
由代表 package (v0.3.0) 於 2019 年 10 月 13 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.