How to make custom y-axis scale in base R

感情迁移 提交于 2021-02-11 15:14:37

问题


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.

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:

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.


回答1:


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.



来源:https://stackoverflow.com/questions/64899146/how-to-make-custom-y-axis-scale-in-base-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!