【问题标题】:Function to plot multiple lines in ggplot在ggplot中绘制多条线的功能
【发布时间】:2021-04-19 06:10:41
【问题描述】:

我正在尝试创建一个函数,该函数采用一系列 x 值和向量以用于方程。对于向量dM 中的每个值,我想计算每个 x 值出现的概率(循环函数中的方程)。将所有概率与关联的 dM 值(所以两列)放在 data.frame 中,然后使用 ggplot 映射线以显示每个关系。

例如:pred_prob(0,870,50,c(-100,0)) 这意味着从 0 到 870 x 50,计算向量中每个值的概率。这是我的工作代码。我怀疑嵌套的 for 循环没有按预期工作,或者存储的数据不正确。

pred_probs <- function(from,to,by,dM){
  pred_females = numeric(0)
  dM <- as.vector(dM)
  x_values <- seq(from = from, to = to, by = by)

  for( j in dM){
   for(i in x_values){
     prob=exp(-2.048e-02*i + 2.087e-02*j + -2.216e-05*i*j)/(1 + exp(-2.048e-02*i + 2.087e-02*j + -2.216e-05*i*j)) 
     pred_females = c(pred_females,prob,j)
   }
  pred_females <- as.data.frame(pred_females)
  ggplot(pred_females) + 
    geom_line(mapping = aes(x = x_values, y = pred_females, 
                            group = j, 
                            color = j))
  }
}
pred_prob(0,870,50,c(-100,0))

编辑:

输出图应如下所示(仅 tw:

编辑(再次): 这个功能满足我的需求:

pred_probs <- function(to, from, by, dep){
tibble() %>% 
  expand(j=dep, i=seq(to, from, by)) %>% 
  mutate(prob=exp(-2.048e-02*i + 2.087e-02*j + -2.216e-05*i*j)/(1 + exp(-2.048e-02*i + 2.087e-02*j + -2.216e-05*i*j))) %>% 
  ggplot() +
  geom_line(aes(x = i, y = prob, color = as.factor(j)))
}
pred_probs(0,870,50,c(-300,-200,-100,0,100))

【问题讨论】:

    标签: r function ggplot2


    【解决方案1】:

    我不完全清楚您要做什么,因为您的代码存在几个问题,但我非常有信心您可以做您想做的事,而无需任何循环或函数。

    这是否接近您想要的?

    library(tidyverse)
    
    tibble() %>% 
      expand(i=c(-200, -100, 0, 100), j=seq(0, 2000, 50)) %>% 
      mutate(prob=exp(-2.048e-02*i + 2.087e-02*j + -2.216e-05*i*j)/(1 + exp(-2.048e-02*i + 2.087e-02*j + -2.216e-05*i*j))) %>% 
      ggplot() +
        geom_line(aes(x = i, y = prob, color = as.factor(j)))
    

    【讨论】:

    • 是的,这正是我需要的,除了在 expand.grid 中切换字母 i 和 j 以绘制向量中不同值的线,而不是序列。我正在制作一个函数,因为有必要更改值序列和向量的值。我将您的代码编辑成一个函数。我在我的问题中发布了最后一个有效的函数。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    相关资源
    最近更新 更多