【发布时间】:2018-07-17 13:22:25
【问题描述】:
我想叠加两个密度图;转换前的数据和转换后的数据之一。我不关心 x 和 y 值,只关心曲线的形状。
我想将给定预测变量的 2 个图表叠加在一起,即使 x 轴不同。我发现很难从两个方面看。实际上,也会有更多的图,因此将未转换和转换的数据合并为一个将是最佳解决方案。
library(tidyverse)
require(caret)
data(BloodBrain)
bbbTrans <- preProcess(select(bbbDescr, adistd, adistm, dpsa3, inthb), method = "YeoJohnson")
bbbTransData <- predict(bbbTrans, select(bbbDescr, adistd, adistm, dpsa3, inthb))
dat <- bbbTransData %>%
gather(Predictor, Value) %>%
mutate(Transformation = "Yeo-Johnson") %>%
bind_rows(data.frame(gather(select(bbbDescr, adistd, adistm, dpsa3, inthb), Predictor, Value), Transformation = "NA", stringsAsFactors = FALSE))
# For the predictor adistd, I would like the x-axis range to be 0:12.5 for the
# "Yeo-Johnson" transformation and 0:250 for no transformation. In this plot, it
# is hard to see the shape of the transformed variables due to the different x-value range.
dat %>% ggplot(aes(x = Value, color = Transformation)) +
geom_density(aes(y = ..scaled..), position = "dodge") +
facet_wrap(~Predictor, scales = "free")
# i.e., I want to superimpose the 2 charts for a given Predictor on top of each other, even though the x-axis is different
# I find it hard to look across the two facets. In reality, as well, there will be a lot more plots, so combining the non-transformed and transformed data into the one plot using colour would be the best solution.
filter(dat, Transformation != 'NA') %>% ggplot(aes(x = Value, y = ..scaled..)) +
geom_density() +
facet_wrap(~Predictor, scales = "free")
filter(dat, Transformation == 'NA') %>% ggplot(aes(x = Value, y = ..scaled..)) +
geom_density() +
facet_wrap(~Predictor, scales = "free")
编辑:我认为我需要的算法是(并且更喜欢使用 tidyverse):
- 按预测变量/转换分组
- 获取每个的密度
- 将 x 的密度转换为 (x-xmin)/(xmax-xmin) 以便介于 0 到 1 之间
- 绘制转换后的密度$x、密度$y
【问题讨论】:
-
那篇文章没有解决如何让密度具有相同的 x 轴范围。添加了编辑以清除我所追求的。我实际上看到了那个(这是我学习使用 ..scaled.. 使 y 轴缩放到 0 和 1 之间的方法)......但我也希望 x 轴缩放到 0 和 1 之间。