Home > Software engineering >  Change number on graph if certain condition occurs
Change number on graph if certain condition occurs

Time:10-08

The code below generates a graph with a few points and a "prediction" line, so to speak. Notice that the number is tending towards a negative number, which in this case is -1.6. Therefore, I would like to do the following: when it happens that the number tends to a negative number, instead of showing that certain negative number in the graph, the value that would appear would be 0. So, for this case, instead of showing -1.6, the number displayed there would be 0.

Executable code below.

library(dplyr)
library(tidyverse)
library(lubridate)


dmda<-"2021-07-07"

datas <- structure(
  list(Code = c("CDE","CDE","CDE","CDE"),
       Days = c(41,42,43,44),
       Numbers = c(5.5,5.5,6,6.5)),
  class = "data.frame", row.names = c(NA, -4L))


f1 <- function(dat, code_nm) {
  dat <- subset(dat,  Code == code_nm)
  
  plot(Numbers ~ Days,  xlim= c(0,45), ylim= c(0,30),
       xaxs='i',data = dat,main = paste0(dmda, "-", code_nm))
  if (var(dat$Numbers)>0){
    
    model <- nls(Numbers ~ b1*Days^2 b2,start = list(b1 = 0,b2 = 0),data = dat, algorithm = "port")
    
    new.data <- data.frame(Days = with(dat, seq(min(Days),max(Days),len = 45)))
    new.data <- rbind(0, new.data)
    lines(new.data$Days,predict(model,newdata = new.data),lwd=2)
    coef<-coef(model)[2]
    points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
    text(.99,coef   1,round(coef,1), cex=1.1,pos=4,offset =1,col="black")} else {
      yz <- unique(dat$Numbers)
      lines(c(0,dat$Days), c(yz, dat$Numbers), lwd = 2)
      points(0, yz, col = "red", pch = 19, cex = 2, xpd = TRUE)
      text(.1,yz  .5,round(yz,1), cex=1.1,pos=4,offset =1,col="black")
    }
  
}

f1(datas, "CDE")

enter image description here

CodePudding user response:

We may use max

f1 <- function(dat, code_nm) {
  dat <- subset(dat,  Code == code_nm)
  
  plot(Numbers ~ Days,  xlim= c(0,45), ylim= c(0,30),
       xaxs='i',data = dat,main = paste0(dmda, "-", code_nm))
  if (var(dat$Numbers)>0){
    
    model <- nls(Numbers ~ b1*Days^2 b2,start = list(b1 = 0,b2 = 0),data = dat, algorithm = "port")
    
    new.data <- data.frame(Days = with(dat, seq(min(Days),max(Days),len = 45)))
    new.data <- rbind(0, new.data)
    lines(new.data$Days,predict(model,newdata = new.data),lwd=2)
    coef<-coef(model)[2]
    points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
    text(.99,coef   1,max(0, round(coef,1)), cex=1.1,pos=4,offset =1,col="black")} else {
      yz <- unique(dat$Numbers)
      lines(c(0,dat$Days), c(yz, dat$Numbers), lwd = 2)
      points(0, yz, col = "red", pch = 19, cex = 2, xpd = TRUE)
      text(.1,yz  .5, round(yz,1), cex=1.1,pos=4,offset =1,col="black")
    }
  
}

-testing

f1(datas, "CDE")

-output

enter image description here

  • Related