ggplot用表达式缩放x轴

时间:2015-11-04 23:08:34

标签: r ggplot2 axis scaletransform

我想转换一个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

enter image description here

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

3 个答案:

答案 0 :(得分:2)

一直在考虑它。认为这就是你想要的:

此代码:

#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 

的产率:

enter image description here

然后我们对它进行转换(使用逆逻辑函数(在基数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

得到以下特性:

enter image description here

答案 1 :(得分:2)

使用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

enter image description here

答案 2 :(得分:1)

删除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))

enter image description here