【问题标题】:How to get a reversed, log10 scale in ggplot2?如何在 ggplot2 中获得反向的 log10 比例?
【发布时间】:2012-06-18 17:08:13
【问题描述】:

我想使用 ggplot2 绘制一个反向的 log10 x 比例图:

require(ggplot2)
df <- data.frame(x=1:10, y=runif(10))
p <- ggplot(data=df, aes(x=x, y=y)) + geom_point() 

但是,我似乎可以要么 log10 比例 反向比例:

p + scale_x_reverse() + scale_x_log10() 

p + scale_x_reverse()

我想这是合乎逻辑的,如果一个层只能有一个比例。当然,我可以通过自己对数据框进行日志转换来破解它,df$xLog &lt;- log10(df$x) 但这种解决方案似乎与 ggplot 的精神背道而驰。有没有办法在不进行 ggplot 调用外部数据转换的情况下获得这种绘图?

【问题讨论】:

  • 我希望这也能正常工作,但显然它有点复杂。有一个work-around 在最新版本中似乎被破坏了。如果@kohske 或其他人无法提出其他解决方案,可能会提出很好的功能请求。

标签: r ggplot2


【解决方案1】:

@joran 在他的评论中给出的链接给出了正确的想法(构建你自己的转换),但是对于ggplot2 现在使用的新的scales 包来说已经过时了。查看 scales 包中的log_transreverse_trans 以获得指导和启发,可以制作一个reverselog_trans 函数:

library("scales")
reverselog_trans <- function(base = exp(1)) {
    trans <- function(x) -log(x, base)
    inv <- function(x) base^(-x)
    trans_new(paste0("reverselog-", format(base)), trans, inv, 
              log_breaks(base = base), 
              domain = c(1e-100, Inf))
}

这可以简单地用作:

p + scale_x_continuous(trans=reverselog_trans(10))

给出了情节:

用一个稍微不同的数据集来证明轴肯定是颠倒的:

DF <- data.frame(x=1:10,  y=1:10)
ggplot(DF, aes(x=x,y=y)) + 
  geom_point() +
  scale_x_continuous(trans=reverselog_trans(10))

【讨论】:

  • 恐怕这个解决方案不再有效:reverselog_trans(10) 中的错误:找不到函数“trans_new”显式添加 scales::trans_new 只会导致新错误,scales 函数似乎已更新:(
  • @Richard 我刚刚检查过它并且它可以工作,但是scales 包必须附加到搜索路径(library("scales"))。答案中并不清楚(当时可能没有必要)。更新中。
  • 这么简单吧?!非常感谢!!
  • 或者使用 :: 表示法从 scales 包中显式调用函数。 --- reverselog_trans &lt;- function(base = exp(1)) { trans &lt;- function(x) -log(x, base) inv &lt;- function(x) base^(-x) scales::trans_new(paste0("reverselog-", format(base)), trans, inv, scales::log_breaks(base = base), domain = c(1e-100, Inf)) }
  • 注意:reverselog_trans 函数已出现在 CRAN cran.r-project.org/web/packages/ACSNMineR/index.html 中(在 ACSNMineR/R/plots.R 中找到)。
【解决方案2】:

ggforce 包具有用于此任务的 trans_reverser() 函数。

library(ggplot2)
library(ggforce)

p <- ggplot() +
  geom_line(aes(x = 1:100, y = 1:100))

p +
  scale_x_continuous(trans = trans_reverser('log10')) +
  annotation_logticks(sides = 'tb') +
  theme_bw()

reprex package (v0.3.0) 于 2020 年 11 月 14 日创建

【讨论】:

    【解决方案3】:

    您可以在 aes() 规范中直接在 ggplot 函数内部应用对数:

    require(ggplot2)
    df <- data.frame(x=1:10, y=runif(10))
    p <- ggplot(data=df, aes(x = log10(x), y=y)) + geom_point() 
    

    然后反转x轴

    p + scale_x_reverse()
    

    这样你的数据不会改变,但你可以缩放图表

    【讨论】:

    • 我喜欢这个答案并且它有效。除了scale_x_reverse(),也可以在上面写-log10(x)
    • 谢谢!我认为-log10(x) 的解决方案很好,但必须小心,因为最终 X 轴为负值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    相关资源
    最近更新 更多