plotting in R with absolute values

1.3k Views Asked by At

I wonder if there is a straightforward way to plot the following two equations in R

x and y are variables and the rest are known parameters.

enter image description here

enter image description here

when X is a vector of dimension n then

enter image description here

enter image description here

1

There are 1 best solutions below

0
On BEST ANSWER

This is a math problem rather than programming. A bit of calculation would help the programming task a lot easier.

First, assume c_1 and c_2 equal zero for simplicity. We can easily recover the original scale by shifting axes. Then, the matrix calculation can be written as follows.

enter image description here

Now let z = ax + by and w = cx + dy. Then, the first equation with absolute value metric would be written as:

enter image description here

From this equation, assuming that gamma is positive, you can visualize z and w as below.

enter image description here

So, you can find a set of (z, w) combinations that satisfy the requirement and convert back to (x, y).

The second equation with the maximum metric can be written as follows:

enter image description here

This implies that (z, w) can be visualized as below.

enter image description here

Again, you can generate such (z, w) pairs and convert back to (x, y).

Here is an R code for the first equation. You can try the second on your own.

library(ggplot2)

# A is (a,b; c,d) matrix
A <- matrix(c(1, 2, -1, 0), 
            nrow=2, ncol=2, byrow=TRUE)
gamma <- 1
c1 <- 0.2
c2 <- 0.1

###############################
z <- seq(-gamma, gamma, length=100)
w <- abs(gamma - abs(z))

z <- c(z, z)
w <- c(w, -w)

qplot(z, w) + coord_fixed()

# computing back (x,y) from (z,w)
z_mat <- rbind(z, w)
x_mat <- solve(A, z_mat)
x <- x_mat[1,] + c1
y <- x_mat[2,] + c2

qplot(x, y) + coord_fixed()
################################