Home > Mobile >  Plot a step (piecewise constant) function in R
Plot a step (piecewise constant) function in R

Time:12-08

Suppose you have the following sample dataset:

rm(list=ls()); set.seed(1)
start<-c(0:4); stop<-c(1:5); Response<- round(10*runif(5) )
Dat<-data.frame(start,stop,Response)
Dat
  start stop Response
1     0    1 3
2     1    2 4
3     2    3 6
4     3    4 9
5     4    5 2

The start/stop is the x-axis. How can I make a plot in R such that between a certain start and stop the y axis takes the constant value in response. i.e. from time 0 to 1 the y-axis takes the value 3, ... ,from time 4 to 5 the y-axis takes the value 2.

CodePudding user response:

Are either of these what you're looking for?

library(ggplot2)

Dat %>% 
    ggplot(aes(start, Response))  
    geom_step()

Dat %>% 
    ggplot()  
    geom_segment(aes(x = start, xend = stop, y = Response, yend = Response)) 
  •  Tags:  
  • r
  • Related