Plot a Step Function in Base R and ggplot2

As an example of a step function, we will use the floor function floor(x) that takes a real number x and returns the greatest integer less than or equal to x.

Coding the floor function in R:

# creating the floor function f(x)
f = function(x) {
  floor(x)
}

# specifying the domain of f(x)
x = seq(-5, 5, length.out = 100) # x contains 100 points between -5 and 5

Plotting in base R

# plotting f(x)
plot(x, f(x), type = 's') # 's' for stairs plot

Output:

Plot of step function in R

We can add the data points to the plot with the following code:

# adding points to the plot
points(x, f(x), pch = 18) # pch specifies the shape of the points

Output:

Plot of step function with data points added to the plot.

Another option would be to plot the points only:

plot(x, f(x), type = 'p', pch = 15) # 'p' for points plot

Output:

Plot of step function as horizontal bars.

Plotting using ggplot2

library(ggplot2)

# creating a data frame that contains x and f(x)
dat = data.frame(x = x, y = f(x))

p = ggplot(dat, aes(x = x, y = y)) + 
  geom_step() # geom_step creates a stairs plot
p

Output:

Plot of a step function using ggplot2.

We can add the data points using the following code:

# adding points to the plot
p + geom_point()

Output:

Plot of step function with data points using ggplot2.

Further reading