简体   繁体   English

Function 到 plot ggplot 中的多行

[英]Function to plot multiple lines in ggplot

I am trying to create a function that takes a sequence of x values and vector to be used in an equation.我正在尝试创建一个 function ,它采用一系列 x 值和向量在方程中使用。 For each value in the vector dM , I would like to calculate probabilities of each x value occurring (equation in function for loop).对于向量dM中的每个值,我想计算每个 x 值出现的概率(function for loop 中的方程)。 Put all probabilities in a data.frame with associated dM values (so two columns) and then use ggplot to map the line to show each relationship.将所有概率与关联的dM值(所以两列)放在 data.frame 中,然后使用 ggplot 到 map 行来显示每个关系。

For example: pred_prob(0,870,50,c(-100,0)) this would mean from 0 to 870 by 50, calculate the probabilities for each value in the vector.例如: pred_prob(0,870,50,c(-100,0))这意味着从 0 到 870 乘 50,计算向量中每个值的概率。 Here is my working code.这是我的工作代码。 I suspect the nested for loop is not working as intended or how the data being stored is not correct.我怀疑嵌套的 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))

EDIT:编辑:

Output graph should look like this (only tw: Output 图应如下所示(仅 tw: 组和颜色变量对应向量中的dM值

EDIT (again): This function satisfies my needs:编辑(再次):这个 function 满足我的需求:

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))

在此处输入图像描述

I'm not entirely clear what you're trying to do as there are several issues with your code, but I'm pretty confident that you can do what you want without any need for loops or functions.我不完全清楚你要做什么,因为你的代码有几个问题,但我非常有信心你可以做你想做的事,而不需要任何循环或函数。

Does this come close to what you want?这是否接近您想要的?

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)))

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM