【问题标题】:Plot negative values in logarithmic scale with ggplot 2使用 ggplot 2 以对数刻度绘制负值
【发布时间】:2014-01-04 18:09:08
【问题描述】:

我需要使用 R 中的 ggplot2 包绘制一个使用 x 对数刻度的带有一些负值的图形。

例如,我想使用 x 对数刻度绘制这些点

x <- c(-1,-10,-100)
y <- c(1,2,3)

我知道 R 中负值的对数会产生 NA 值,但我需要这样的结果:

这可以使用ggplot2吗?

【问题讨论】:

    标签: r ggplot2 log-analysis


    【解决方案1】:

    为此,我从ggallin package 中找到了pseudolog10_trans 转换 非常有帮助,因为它可以适应对数刻度上正数和负数的情况。例如

    library(ggplot2)
    library(ggallin)
    
    x <- c(-1,-10,-100, 1, 10, 100)
    y <- c(1,2,3, 1,2,3)
    
    df = data.frame(x = x, y = y)
    
    My_Plot = ggplot(
        df, 
        aes(x=x, y=y)) + 
        geom_point() + 
        scale_x_continuous(trans = pseudolog10_trans)
    
    My_Plot
    

    【讨论】:

      【解决方案2】:

      有两个问题需要解决 - 从负值计算对数,然后结合对数刻度和反向刻度。

      要结合对数和反向比例,您可以使用@Briand Diggs 在this SO question 上提供的解决方案。

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

      要使其适用于负值,请在 ggplot() 调用中将 x 值作为 -x 提供,然后在 scale_x_continuous() 内对 labels= 使用另一个转换以获取负值。

      df<-data.frame(x=c(-1,-10,-100),y= c(1,2,3))
      ggplot(df,aes(-x,y))+geom_point()+
        scale_x_continuous(trans=reverselog_trans(base=10),
                           labels=trans_format("identity", function(x) -x))
      

      【讨论】:

      • 另一个问题..如果我在 x 轴上也有正数据,我该怎么办?例如'x
      • 那么,您如何解释动态图表中对数缩放轴的可能性,即使是负值?
      猜你喜欢
      • 2017-09-08
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多