如何在基础 R 中制作自定义 y 轴比例 [英] How to make custom y-axis scale in base R

查看:52
本文介绍了如何在基础 R 中制作自定义 y 轴比例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何使用自定义 y 轴比例在 R 中制作绘图.例如,我想绘制一个与下面相同的 y 轴的图.即使实际数字距离不同,您也可以使刻度线之间的距离相同.

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)

结果如下:

然而,图表中的数据都在错误的地方,因为它与新的 y 轴比例不匹配.所以我想要的是在 y 轴上获得我想要的任何比例,然后能够根据 y 轴正确绘制我的数据.

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.

推荐答案

这有点奇怪.y 轴是几乎 对数的,但不完全是对数,因为刻度线在比下面的大 3 倍和 3.333 倍之间交替.这并不适合直接转换.但是,如果我们对 y 轴位置和 y 值本身进行 log 变换,我们可以使标记和绘图位置准确,但代价是刻度线的间距稍微不均匀.

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))

请注意,没有一个负值可以绘制在这个比例上,因为0"在像这样的对数尺度上会无限远,因此没有定义负数.

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.

这篇关于如何在基础 R 中制作自定义 y 轴比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆