Home > Back-end >  How insert point on the axis of a graph
How insert point on the axis of a graph

Time:09-26

I would like some help with the following question:

As you can see, the graph below generates a graph with dots and a line. This is a trend line. ​Therefore, I would like to do two things: (1) is that the point in red stays on the axis of the graph and (2) is that the line goes to the point in red

Executable code below:

Note: I inserted an image to illustrate what I want

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

#dataset df1
df1 <- structure(
  list(date1 = c("2021-06-28","2021-06-28","2021-06-28","2021-06-28","2021-06-28",
                 "2021-06-28","2021-06-28","2021-06-28"),
       date2 = c("2021-04-02","2021-04-03","2021-04-08","2021-04-09","2021-04-10","2021-07-01","2021-07-02","2021-07-03"),
       Week= c("Friday","Saturday","Thursday","Friday","Saturday","Thursday","Friday","Monday"),
       DR01 = c(4,1,4,3,3,4,3,6), DR02= c(4,2,6,7,3,2,7,4),DR03= c(9,5,4,3,3,2,1,5),
       DR04 = c(5,4,3,3,6,2,1,9),DR05 = c(5,4,5,3,6,2,1,9),
       DR06 = c(2,4,3,3,5,6,7,8),DR07 = c(2,5,4,4,9,4,7,8)),
  class = "data.frame", row.names = c(NA, -8L))

#Generate graph

dmda<-"2021-07-01"

datas<-df1 %>%
  filter(date2 == ymd(dmda)) %>%
  summarize(across(starts_with("DR"), sum)) %>%
  pivot_longer(everything(), names_pattern = "DR(. )", values_to = "val") %>%
  mutate(name = as.numeric(name))
colnames(datas)<-c("Days","Numbers")

attach(datas)
plot(Numbers ~ Days, data=datas, xlim=c(0,7), ylim=c(0,20))

model <- nls(Numbers ~ b1*Days^2 b2, data=datas, start = list(b1 = 47,b2 = 0))

new.data <- data.frame(Days = seq(min(Days),max(Days),len = 45))
lines(new.data$Days,predict(model,newdata = new.data))
points(0, coef(model)[2], col="red",pch=19,cex = 1.2)

enter image description here

Example of how i want

enter image description here

CodePudding user response:

You could just rbind a zero to new.data in this case, it's value on the y axis will then be predicted together with the other values. xaxs='i' will draw the x axis exactly at zero. For the point we use xpd=TRUE to allow overlap.

plot(Numbers ~ Days, data=datas, xlim=c(0, 7.5), ylim=c(0, 20), xaxs='i')

new.data <- rbind(0, new.data)
lines(new.data$Days, predict(model, newdata=new.data))
points(0, coef(model)[2], col="red", pch=19, cex=1.2, xpd=TRUE)

enter image description here

  • Related