John Smith
John Smith

Reputation: 187

How to make custom y-axis scale in base R

I am trying to figure out how to make a plot in R with a custom y-axis scale. For, example I would like to make a plot with the same y-axis as below. You can the distance between the tick marks is the same even though the actual numerical distance is not.

enter image description here

In order to achieve the same axis look, I can do the following:

set.seed(1)

n <- 10
x <- 1:n
y <- rnorm(n)

ticks <- c("1/30","1/10","1/3","1","3","10","30")


plot(x, y, axes = FALSE, ylim = c(-3,3))
axis(1)
axis(2, seq(-3,3,1), ticks)

which results in the following:

enter image description here

however, the data in the graph is all in the wrong places since it doesn't match the new y-axis scale. So what I want is to get whatever scale I want on the y-axis and then to be able to plot my data correctly according to the y-axis.

Upvotes: 1

Views: 1279

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173803

This is a bit of a strange one. The y axis is almost logarithmic, but not quite, since the tick marks alternate between being 3 times and 3.333 times greater than the one below. This doesn't lend itself to a straightforward transformation. However, we can make the labelling and plotting positions accurate at the expense of having the tick marks slightly unevenly spaced if we log transform the y axis positions and y values themselves.

set.seed(1)

n <- 10
x <- 1:n
y <- rnorm(n)

ticks <- c("1/30","1/10","1/3","1","3","10","30")

tick_nums <- c(1/30, 1/10, 1/3, 1, 3, 10, 30)

plot(x, log(y, 3), axes = FALSE, ylim = c(-3,3))
#> Warning in xy.coords(x, y, xlabel, ylabel, log): NaNs produced
axis(1)
axis(2, at = log(tick_nums, 3), ticks)

We can show these points are in the correct position by doing:

text(x = x, y = log(y * 1.3, 3), label = round(y, 3))

Note that none of the negative values can be plotted on this scale, since "0" on a logarithmic scale like this would be infinitely far down and negative numbers are not therefore not defined.

Upvotes: 4

Related Questions