ggplot 用表达式缩放 x 轴

ggplot scale x axis with an expression

我想转换 ggplot 图,使 0.9、0.99、0.999、0.9999 等在 x 轴上彼此的距离相等。

在下面的示例中,这些分隔符集中在右侧。我希望在 x 轴上拉伸更高的值。这与压缩较大值的对数刻度相反。

p <- seq(0.001, 1, 0.001)
d <- seq(1, 1000)
percentile <- data.frame(p, d)
g1 <- ggplot(percentile, aes(p, d))
g1 <- g1 + geom_point()
g1 <- g1 + scale_x_continuous(breaks=c(0,0.9,.9,.99,.999,.9999))
g1

我想我需要用像 log(1/(1-p)) 这样的表达式缩放 x 轴,但我不确定如何用任意表达式缩放。

删除 scale_x_continuous 并使用

g1 + scale_x_log10(breaks=c(0,0.9,.9,.99,.999,.9999))

但是你会遇到 breaks == 0 的问题,因为 log10(0) = -Inf

例如:

p <- seq(0.001, 1, 0.001)
d <- seq(1, 1000)
percentile <- data.frame(p, d)
g1 <- ggplot(percentile, aes(p, d))
g1 <- g1 + geom_point()
g1 <- g1 + scale_x_log10(breaks=c(0.9,.9,.99,.999,.9999)) + xlim(c(.9,1))

一直在想。认为这就是您想要的:

此代码:

#Generate our Data

p <- seq(0.001, 1-0.001, 0.001)
sin_p <- sin(p*pi)
xin <- c( 0.5,0.9,0.99,0.999 )
lxin <- as.character(xin)
pctdf <- data.frame(p,sinp)

# Plot it in raw form
g1 <- ggplot(pctdf, aes(p, sin_p)) +
  geom_point() +
  geom_vline(xintercept=xin,color="red") +
  labs(title="Raw")+
  scale_x_continuous(breaks=xin,labels=xin) +
  theme(axis.text.x = element_text(size = rel(1.0),angle=-90,hjust=0))
g1 

产量:

然后我们对其进行变换(使用逆逻辑函数(以 10 为基数)):

# Now transform it
transform <- function(x){
  -log10(((1/x) - 1))
}
xin <- transform(xin)
pctdf$p <- transform(pctdf$p)

# Plot it

g2 <- ggplot(pctdf, aes(p, sin_p)) +
  geom_point() +
  geom_vline(xintercept=xin,color="red") +
  labs(title="Transformed")+
  scale_x_continuous(breaks=xin,labels=lxin) +
  theme(axis.text.x = element_text(size = rel(1.0),angle=-90,hjust=0))
g2

产量:

使用以下 Mike Wise 的回答作为模板,我能够使它正常工作。这是我想出的代码:

transform <- function(x){
  log(1/(1-x))
}
p <- transform(seq(0.001, 1, 0.001))
d <- seq(1, 1000)
xin <- transform(c(0.5,0.9,0.99,0.999))
lxin <- as.character(c(0.5,0.9,0.99,0.999))
percentile <- data.frame(p, d)
g1 <- ggplot(percentile, aes(p, d))
g1 <- g1 + geom_point()
g1 <- g1 + scale_x_continuous(breaks=xin, labels=lxin)
g1