Bobak Digital
Bobak Digital

Reputation: 75

R : Plotting a point on the Y axis when the X axis is using a log scale

I'm making a plot in R I'd like to have a symbol appear at a specific point (say, alpha) on my y axis. My x axis uses a log-scale so I don't think I can use the xy coordinates (0, alpha) to plot the point (I may be wrong).

I've tried something like this:

W.range <- range(W)
Z.range <- range(Z1, Z2)
# Draw Empty Graph 
plot(W.range, Z.range, type="n", log="x")
# First Curve
lines(W, Z1, type="l", lty=1, lwd=1.5, col=1)
# Second Curve
lines(W, Z2, type="l", lty=2, lwd=1.5, col=2)
# Plot Single Point on vertical axis at level alpha (for some constant alpha)
points(x=0, y=alpha, pch=1, col=1)

However, I get errors relating to the x=0 coordinate. Advice? As always, I appreciate the suggestions.

Upvotes: 0

Views: 7662

Answers (1)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162341

This should work, subbing in your own data as appropriate:

# Example data and plot
x <- y <- 1:100
alpha <- 44
plot(x,y, log="x", type="l")    

# Add point
points(x = 10^(par("usr")[1]), 
       y = alpha, 
       pch = 16, cex=1.3, col = "red", las = 1,
       xpd = TRUE) # controls whether or not pts straddling the axis are clipped

enter image description here

To understand what I did here, have a look at ?par, which I use here both to query and to set graphical parameters.

In particular, here is the description of par("usr"), from the help file linked above:

‘usr’ A vector of the form ‘c(x1, x2, y1, y2)’ giving the extremes
      of the user coordinates of the plotting region.  When a
      logarithmic scale is in use (i.e., ‘par("xlog")’ is true, see
      below), then the x-limits will be ‘10 ^ par("usr")[1:2]’.
      Similarly for the y-axis.

The x-coordinates returned by usr are in terms of the log-transformed values of x. Thus, to get a point placed on the y-axis, you need to give it an x coordinate such that it's log (base 10) is equal to the location of the y-axis, expressed in user coordinates. par("usr")[1] gets you the location of the lower limit of the x-axis: 10^(par("usr")[1] gets you the x-value that will be plotted to just that part of the x-axis.

Upvotes: 7

Related Questions