ggplot缩放与日志转换的区别

问题描述 投票:0回答:1

我有以下偏差数据:

set.seed(3)
x <- rgamma(1e6, 0.1, .2)

summary(log(x))
#     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
# -170.637  -12.760   -5.825   -8.828   -1.745    3.807 

查看数据的对数转换分布

summary(log(x))
#     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
# -170.637  -12.760   -5.825   -8.828   -1.745    3.807 

通过转换可视化数据:

ggplot(data.frame(x), aes(x)) + 
  geom_histogram(bins = 100) + 
  scale_x_continuous(trans = "log")

enter image description here

ggplot中日志转换和缩放的差异是什么原因?我看到通过看x轴有区别。摘要中的最小值是-170.637,而图的值在5.8e-62范围内。

更新:

g1 <- ggplot(data.frame(x), aes(x)) + geom_histogram(bins = 100)
g2 <- ggplot(data.frame(x), aes(x)) + geom_histogram(bins = 100) + scale_x_continuous(trans = "log")
g3 <- ggplot(data.frame(x), aes(log(x))) + geom_histogram(bins = 100)
gridExtra::grid.arrange(g1, g2, g3, ncol=3)

enter image description here

g1 <- ggplot(data.frame(x), aes(x)) + geom_histogram(bins = 100)
g2 <- ggplot(data.frame(x), aes(x)) + geom_histogram(bins = 100) + scale_x_log10()
g3 <- ggplot(data.frame(x), aes(log10(x))) + geom_histogram(bins = 100)
gridExtra::grid.arrange(g1, g2, g3, ncol=3)

enter image description here

r ggplot2
1个回答
2
投票

你可能更容易看到你是否使用scale_x_log10

ggplot(data.frame(x), aes(x)) + 
  geom_histogram(bins = 100) + 
  scale_x_log10()

enter image description here

然后,我们可以做一些比较。首先,我们可以更改标签:

myBreaks <-
  10^c(-61, -43, -25, -7)

ggplot(data.frame(x), aes(x)) + 
  geom_histogram(bins = 100) + 
  scale_x_log10(breaks = myBreaks
                , labels = log10(myBreaks))

enter image description here

我们也可以通过在绘制之前转换x获得相同的情节:

ggplot(data.frame(x = log10(x)), aes(x)) + 
  geom_histogram(bins = 100)

enter image description here

并且,我们可以将所有这些与log10(x)的摘要进行比较

    Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
-74.1065  -5.5416  -2.5300  -3.8340  -0.7579   1.6531 

看看它与上面的图表如何匹配?

scale_x_log10scale_x_continuous(trans = "log")实际上并没有改变数据 - 它们正在改变轴的缩放比例,但是将标签留在原始单位中。

将它恢复到原始值,log(5.8e-62)-141 - 如果绘图是转换后的数据,这是您期望看到的值。

如果您确实必须显示日志值,您还可以在映射中完成该操作,并且还有一个额外的好处,即轴标签默认为有意义的值:

ggplot(data.frame(x = x), aes(log10(x))) + 
  geom_histogram(bins = 100)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.