rplotaxis

How to put infinity and -infinity on a graph with plot


In the attached image I want to replace -1 by -Inf and 3 by Inf.

enter image description here

This is the code:

F <- function(x) {
  f <- NULL
  f[x < 0] <- 0
  f[x >= 0 & x < 1] <- 0.4*x[x >= 0 & x < 1]^2
  f[x >= 1 & x < 2] <- 0.2*x[x >= 1 & x < 2]^2 + (0.2)
  f[x >= 2] <- 1
  f
}
x <- seq(-1, 3, 0.01)
plot(x, F(x), type="l", las=1)

Solution

  • Use xaxt='n' to omit x-axis. axTicks(1) gives you current tick positions; you can replace first and last element and replace them with custom stuff.

    plot(x, F(x), type="l", las=1, xaxt='n')
    at1 <- axTicks(1)
    at1[c(1, length(at1))] <- c('-Inf', 'Inf')
    axis(1, at=axTicks(1), labels=at1)
    

    enter image description here

    You could also use the symbols using expressions.

    plot(x, F(x), type="l", las=1, xaxt='n')
    at1 <- axTicks(1)
    at1[c(1, length(at1))] <- expression(-infinity, infinity)
    axis(1, at=axTicks(1), labels=at1)
    

    enter image description here