【问题标题】:ggplot scale x axis with an expressionggplot用表达式缩放x轴
【发布时间】:2015-11-04 23:08:34
【问题描述】:

我想转换一个 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 轴,但我不确定如何通过任意表达式来缩放。

【问题讨论】:

  • 但那将是一条凹曲线而不是一条直线
  • 当然可以,但我认为这对我来说没问题。
  • 你在下面看到我的解决方案了吗?

标签: r ggplot2 axis scaletransform


【解决方案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

屈服:

【讨论】:

  • 嗨,迈克,感谢您的回复。这绝对足够接近我所需要的。我能够使用您的解决方案来制作我正在寻找的解决方案。为了完整起见,我将发布对我有用的代码。
【解决方案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

【讨论】:

    【解决方案3】:

    删除scale_x_continuous 并使用

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

    但是由于log10(0) = -Inf,您将遇到breaks == 0 的问题

    例如:

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

    【讨论】:

    • 谢谢,但我认为这与我想要的相反,因为对数刻度会随着值的增长而压缩,我想随着它们的增长而扩展它们。
    猜你喜欢
    • 2016-10-12
    • 1970-01-01
    • 2021-06-14
    • 2020-10-29
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多