简体   繁体   中英

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. For each value in the vector dM , I would like to calculate probabilities of each x value occurring (equation in 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.

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

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: 组和颜色变量对应向量中的dM值

EDIT (again): This function satisfies my needs:

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

在此处输入图像描述

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.

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