在没有明确指定中断的情

Dre*_*een 6 r ggplot2

我发现使用时ggplot2有时会产生太少的刻痕scale_y_log10.我试图从任意数据自动生成绘图,我正在寻找一种方法来增加刻度线的数量而不明确指定它们(因为我事先不知道数据是什么).例如,这是一个使用log-y-scale创建简单散点图的函数:

example_plot <- function(x) {
  p <- ggplot(d, aes(x=MW, y=rel.Ki)) + 
    geom_point() +
    scale_y_log10()
  p
}
Run Code Online (Sandbox Code Playgroud)

这通常会很好,但有以下数据

d <- structure(list(MW = c(89.09, 174.2, 147.13, 75.07, 131.17, 131.17, 146.19, 149.21, 165.19, 115.13, 181.19, 117.15), rel.Ki = c(2.91438577473767, 1, 1.07761254731238, 1.0475715900998, 0.960123906592881, 0.480428471483881,  1.50210548081627, 0.318457530434953, 0.458477212731015, 1.92246139937586,  0.604121577795352, 2.4111345825694)), .Names = c("MW", "rel.Ki"), class = "data.frame", row.names = c(1L, 6L, 11L, 16L, 21L, 26L, 31L, 36L, 41L, 47L, 54L, 59L))
Run Code Online (Sandbox Code Playgroud)

它产生

print(example_plot(d))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

y轴上的单个刻度标记不是很有用.有没有办法可以防止这种情况,而不是重写自动蜱位拣选功能?

Mar*_*ius 8

我刚刚通过阅读发现的一个有趣的发现?continuous_scale是,breaks论证可以是:

一个函数,当使用单个参数调用时,给出比例限制的字符向量返回一个字符向量,指定要显示的中断.

因此,为了保证一定数量的休息时间,您可以执行以下操作:

break_setter = function(lims) {
  return(seq(from=as.numeric(lims[1]), to=as.numeric(lims[2]), length.out=5))
}

ggplot(d, aes(x=MW, y=rel.Ki)) + 
    geom_point() +
    scale_y_log10(breaks=break_setter)
Run Code Online (Sandbox Code Playgroud)

显然,非常简单的示例函数不能很好地适应数据的对数性质,但它确实显示了如何以编程方式更多地处理这一问题.


你也可以使用pretty,它建议一些休息时间并返回漂亮的整数.运用

break_setter = function(lims) {
    return(pretty(x = as.numeric(lims), n = 5))
}
Run Code Online (Sandbox Code Playgroud)

产生以下结果:

logbreaks

更好的是,我们可以根据您的需要break_setter()返回一个合适的函数,n默认值为5.

break_setter = function(n = 5) {
   function(lims) {pretty(x = as.numeric(lims), n = n)}
}

ggplot(d, aes(x=MW, y=rel.Ki)) + 
    geom_point() +
    scale_y_log10(breaks=break_setter())  ## 5 breaks as above

ggplot(d, aes(x=MW, y=rel.Ki)) + 
    geom_point() +
    scale_y_log10(breaks=break_setter(20))
Run Code Online (Sandbox Code Playgroud)