简体   繁体   English

R中的标签对数刻度显示

[英]Labelling logarithmic scale display in R

在绘制组织图,散点图和其他图(轴的比例缩放为R的对数)时,如何使用诸如10 ^ -1 10 ^ 0 10 ^ 1 10 ^ 2 10 ^ 3之类的标签代替显示的轴只是-1、0、1、2、3等。应该在命令中添加哪些参数,例如hist(),plot()等?

Apart from the solution of ggplot2 (see gsk3's comment), I would like to add that this happens automatically in plot() as well when using the correct arguments, eg : 除了ggplot2的解决方案(请参阅gsk3的注释)之外,我还要补充一点,当使用正确的参数时,这也会在plot()中自动发生,例如:

x <- 1:10
y <- exp(1:10)
plot(x,y,log="y")

You can use the parameter log="x" for the X axis, or log="xy" for both. 您可以将参数log="x"用于X轴,或者将log="xy"用于两者。

If you want to format the numbers, or you have the data in log format, you can do a workaround using axis(). 如果要格式化数字,或者数据具有对数格式,则可以使用axis()来解决。 Some interesting functions : 一些有趣的功能:

  • axTicks(x) gives you the location of the ticks on the X-axis (x=1) or Y-axis (x=2) axTicks(x)提供刻度线在X轴(x = 1)或Y轴(x = 2)上的位置
  • bquote() converts expressions to language, but can replace a variable with its value. bquote()将表达式转换为语言,但可以用其值替换变量。 More information on bquote() in the question Latex and variables in plot label in R? 有关乳胶问题和R中情节标签中的变量的 bquote()更多信息 .
  • as.expression() makes the language object coming from bquote() an expression. as.expression()使来自bquote()的语言对象成为表达式。 This allows axis() to do the formatting as explained in ?plotmath . 这允许axis()进行格式化,如?plotmath It can't do so with language objects. 语言对象无法做到这一点。

An example for nice formatting : 一个漂亮的格式化示例:

x <- y <- 1:10
plot(x,y,yaxt="n")
aty <- axTicks(2)
labels <- sapply(aty,function(i)
            as.expression(bquote(10^ .(i)))
          )
axis(2,at=aty,labels=labels)

Which gives 这使

在此处输入图片说明

Here is a different way to draw this type of axis: 这是绘制此类型轴的另一种方法:

plot(NA, xlim=c(0,10), ylim=c(1, 10^4), xlab="x", ylab="y", log="y", yaxt="n")
at.y <- outer(1:9, 10^(0:4))
lab.y <- ifelse(log10(at.y) %% 1 == 0, at.y, NA)
axis(2, at=at.y, labels=lab.y, las=1)

在此处输入图片说明

EDIT: This is also solved in latticeExtra with scale.components 编辑:这也解决了latticeExtrascale.components

In ggplot2 you just can add a 在ggplot2中,您可以添加一个

... + 
scale_x_log10() + 
scale_y_log10(limits = c(1e-4,1), breaks=c(1e-4,1e-3,1e-2,0.1,1)) + ...

to scale your axis, Label them and add custom breaks. 缩放轴,标记它们并添加自定义间隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM