Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a circle in a log-log plot in R?

I have a plot with two logarithmic axes. I'd like to add a circle to a certain position of the plot. I tried to use plotrix, but this does not give options for "log-radius".

# data to plot
x = 10^(-1 * c(5:0))
y = x ^-1.5

#install.packages("plotrix", dependencies=T)
# use require() within functions
library("plotrix")

plot (x, y, log="xy", type="o")
draw.circle(x=1e-2, y=1e2, radius=1e1, col=2)

How can I add a circle to my log-log plot?

like image 564
R_User Avatar asked Dec 09 '22 16:12

R_User


1 Answers

As krlmlr suggests, the easiest solution is to slightly modify plotrix::draw.circle(). The log-log coordinate system distorts coordinates of a circle given in the linear scale; to counteract that, you just need to exponentiate the calculated coordinates, as I've done in the lines marked with ## <- in the code below:

library("plotrix")

draw.circle.loglog <- 
function (x, y, radius, nv = 100, border = NULL, col = NA, lty = 1,
    lwd = 1)
{
    xylim <- par("usr")
    plotdim <- par("pin")
    ymult <- (xylim[4] - xylim[3])/(xylim[2] - xylim[1]) * plotdim[1]/plotdim[2]
    angle.inc <- 2 * pi/nv
    angles <- seq(0, 2 * pi - angle.inc, by = angle.inc)
    if (length(col) < length(radius))
        col <- rep(col, length.out = length(radius))
    for (circle in 1:length(radius)) {
        xv <- exp(cos(angles) * log(radius[circle])) * x[circle]         ## <-
        yv <- exp(sin(angles) * ymult * log(radius[circle])) * y[circle] ## <-
        polygon(xv, yv, border = border, col = col[circle], lty = lty,
            lwd = lwd)
    }
    invisible(list(x = xv, y = yv))
}

# Try it out 
x = 10^(-1 * c(5:0))
y = x ^-1.5

plot (x, y, log="xy", type="o")
draw.circle.loglog(x = c(1e-2, 1e-3, 1e-4), y = c(1e2, 1e6, 1e2),
                   radius = c(2,4,8), col = 1:3)

enter image description here

like image 91
Josh O'Brien Avatar answered Dec 11 '22 08:12

Josh O'Brien