R ggplot,两个鳞片在一起

Yil*_*ang 1 plot axis r scale ggplot2

我希望缩放y轴:

  1. 通过log10,我用过:

    scale_y_log10(breaks = trans_breaks("log10",function(x)10 ^ x))

  2. 更多刻度:

    scale_y_continuous(断裂= pretty_breaks(10))

但是从错误消息中,只能有一个比例.有没有办法同时拥有这两个尺度?

pan*_*gia 8

如果我理解你的问题,你希望在对数刻度上有一个轴,而不仅仅是1,10,100等等.这是一个可重复的例子,描述了你的尝试:

library(ggplot2)
library(scales)
dat <- data.frame(X=1:3, Y=c(2,50,10000))
ggplot(data=dat, aes(x=X, y=Y)) + geom_point() + 
  scale_y_log10(breaks=trans_breaks("log10",function(x) 10^x)) +
  scale_y_continuous(breaks=pretty_breaks(10))

## Error: Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale.
Run Code Online (Sandbox Code Playgroud)

好的,这个错误说我们只允许一次通话scale_y_something.既然你想要对数比例,那就让我们保持scale_y_log10.我们从这里开始的方法取决于你想要达到的目标 - 即使它们不是很好的圆形数字,它是否可以简单地沿轴线间隔更均匀的刻度?如果是这样,你可以pretty()通过选择一个高于正常值的值来增加额外的休息时间n(?trans_breaks将传递给的承诺pretty):

ggplot(data=dat, aes(x=X, y=Y)) + geom_point() + 
  scale_y_log10(breaks=trans_breaks("log10", function(x) 10^x, n=20))
Run Code Online (Sandbox Code Playgroud)

灵活,也许,但丑陋.您可以通过将结果应用于数据来探索trans_breaks正在做什么(dat$Y在此示例中).请注意,值n被视为建议而不是命令:

trans_breaks("log10", function(x) 10^x, n=2 )(dat$Y)
[1]     1   100 10000

trans_breaks("log10", function(x) 10^x, n=10)(dat$Y)
[1]     1.000     3.162    10.000    31.623   100.000   316.228  1000.000  3162.278 10000.000
Run Code Online (Sandbox Code Playgroud)

或者你可能更喜欢1,3,10,30,100等形式的刻度?如果是这样:

ggplot(data=dat, aes(x=X, y=Y)) + geom_point() + 
  scale_y_log10(breaks=c(1,3,10,30,100,300,1000,3000,10000))
Run Code Online (Sandbox Code Playgroud)

我猜这些直接规格是你最好的选择.但是,如果您还需要任意y范围的灵活性,请从/sf/answers/998118691/获取提示并添加标签参数:

ggplot(data=dat, aes(x=X, y=Y)) + geom_point() + 
  scale_y_log10(breaks=trans_breaks("log10", function(x) 10^x, n=20), 
                labels=trans_format("log10", math_format(10^.x)))
Run Code Online (Sandbox Code Playgroud)