简体   繁体   中英

Plot a step (piecewise constant) function in R

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. ie from time 0 to 1 the y-axis takes the value 3, ... ,from time 4 to 5 the y-axis takes the value 2.

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

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