【问题标题】:ggplot2: Plot of function with different lines for each parameter valueggplot2:每个参数值具有不同线条的函数图
【发布时间】:2019-10-14 06:05:52
【问题描述】:

如何根据公式中不同的参数值绘制多条不同的线兼点曲线?

我想绘制一个简单的公式,比如复利。 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 循环吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以尝试使用dplyr 构建数据框并将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))
    

    reprex package (v0.3.0) 于 2019 年 10 月 13 日创建

    【讨论】:

    • 我对 tidyverse 不熟悉,并且仍在努力用通常的 R 来解决这个问题。我确实以一种非常低效的方式得到了绘图:参数的每个值都有一个单独的数据框。有什么想法吗?
    • 除非您显示您正在使用的代码,否则我无法真正帮助您。如果它与原始问题的距离不太远,请考虑编辑您的原始帖子以显示第二次尝试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    相关资源
    最近更新 更多