Есть ли способ построить линии t = 300, 350, 450 и 500 на одном графике? - PullRequest
1 голос
/ 07 мая 2020

введите здесь описание изображения Я хотел построить несколько линий на одном графике, но не мог понять, какой код использовать. Кроме того, есть ли способ назначить цвет каждой из линий? Просто новичок в Rstudio, и мне было поручено подбирать чью-то работу, поэтому я делал много проб и ошибок, но последние несколько дней мне не везло. Надеюсь, кто-нибудь сможет мне с этим помочь! Большое спасибо


ecdf.shift <- function(OUR_threshold, des_cap = 40, nint = 10000){

  #create some empty vectors for later use in the loop

  ecdf_med = c() 
  ecdf_obs = c()

  for (i in 1:length(OUR_threshold)){

    # filter out the OUR threshold data, then select only the capture column and create a ecdf function

    ecdf_fun <- HRP_rESS_no %>% 
      filter(ESS > OUR_threshold[i]) %>%
      .$TSS_con %>%
      ecdf()

    # extract the ecdf data and put in tibble dataframe, then create a linear interpolation of the curve. 

    ecdf_data <- tibble(TSS_con = environment(ecdf_fun)$x, prob = environment(ecdf_fun)$y)
    ecdf_interpol <- approx(x = ecdf_data$TSS_con, y = ecdf_data$prob, n = nint)

    # find the vector numbers in x which correspond with the desired capture. Then find correlate the vectornumbers with probability numbers in the y vectors. Take the median value in case multiple hits. Put this number in a vector with designed vectornumber as ditacted by the loopnumber i. 



    ecdf_med[i] <- median(ecdf_interpol$y[(round(ecdf_interpol$x,1) == des_cap)])



    # calculate the number of observations when the filtering takes place. 

    ecdf_obs[i] <- HRP_rESS_no %>% 
      filter(ESS > OUR_threshold[i]) %>%
      .$TSS_con %>%
      length()

    # Flush the ecdf data. The ecdf is encoded as a function with global paramaters, so you want to reset them everytime the loop is done to avoid pesky bugs to appear. 

    rm(ecdf_data)
  }

  #create a tibble dataframe with all the loop data. 

  ecdf_out <- tibble(OUR_ratio_cutoff = OUR_threshold, prob = (ecdf_med)*100, nobs = ecdf_obs)



  return(ecdf_out)

}

ratio_threshold <- seq(0,115, by = 5)
t = ecdf_MLSS_target <- 400 %>% 
 ecdf.shift(ratio_threshold, .) %>% 
  filter(nobs > 2) %>%
  ggplot(aes( x = OUR_ratio_cutoff, y = prob)) + 
  geom_line() + 
  geom_point() + 
  theme_bw(base_size = 12) +
  theme(panel.grid = element_blank()) +
  scale_y_continuous(limits = c(0,100), 
                     breaks = seq(0,300, by = 5), 
                     expand = c(0,0)) +
  scale_x_continuous(limits = c(0,120), 
                     breaks = seq(0,110, by = 10), 
                     expand = c(0,0)) +
  labs(x = "ESS mg TSS/L",
       y = "Probability of contactor MLSS > 400 mg TSS/L ")




plot(t)

1 Ответ

0 голосов
/ 07 мая 2020

Проще всего было бы сначала l oop по вашим различным значениям t и объединить полученные фреймы данных в один большой фрейм данных и использовать это для своего графика. Ваш код воспроизводится не полностью (для этого требуются данные, которых у нас нет, например HRP_rESS_no). Итак, я урезал эту функцию до самого ядра - создал фрейм данных, который делает разные «линии» в зависимости от вашего значения t. Я просто использовал его как склон.

Надеюсь, идея понятна.

library(tidyverse)

ecdf.shift <- function(OUR_threshold, t) {
  data.frame(x = OUR_threshold, y = t * OUR_threshold)
}

ratio_threshold <- seq(0, 115, by = 5)

t_df <-
  map(1:5, function(t) ecdf.shift(ratio_threshold, t)) %>%
  bind_rows(, .id = "t")

ggplot(t_df, aes(x, y, color = t)) +
  geom_line() +
  geom_point()

Создано 07.05.2020 с помощью пакета REPEX (v0.3.0)

...