使用ggplot 2在对数刻度下绘制负值。

11
我需要使用R中的ggplot2包来绘制带有负值的图表,并使用对数刻度x轴。
例如,我想使用对数刻度x轴来绘制这些点:
x <- c(-1,-10,-100)
y <- c(1,2,3)

我知道在R中对负值取对数会产生NA值,但我需要像这样的结果:
这可以使用ggplot2来实现吗?
2个回答

16

对于这个问题,我发现来自ggallinpseudolog10_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

9
有两个问题需要解决——计算负值的对数,以及将对数刻度和反向刻度结合起来。
要结合对数和反向刻度,您可以使用@Briand Diggs在这个SO问题上提供的解决方案。
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))

enter image description here


2
另一个问题是,如果我的x轴上也有正数据,我该怎么办?例如 'x <- c(-10,1,10)'... - Dalmo1991
那么,你如何解释在运动图表中即使存在负值,也能够进行对数缩放轴的可能性呢? - CBechet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接