gpt4 book ai didi

r - 如何在 ggplot 中重现 smoothScatter 的离群值绘图?

转载 作者:行者123 更新时间:2023-12-02 05:07:12 25 4
gpt4 key购买 nike

我正在尝试获得类似 smoothScatter 函数的功能,但仅在 ggplot 中。除了绘制 N 个最稀疏的点之外,我已经弄清楚了一切。谁能帮我解决这个问题吗?

library(grDevices)
library(ggplot2)

# Make two new devices
dev.new()
dev1 <- dev.cur()
dev.new()
dev2 <- dev.cur()

# Make some data that needs to be plotted on log scales
mydata <- data.frame(x=exp(rnorm(10000)), y=exp(rnorm(10000)))

# Plot the smoothScatter version
dev.set(dev1)
with(mydata, smoothScatter(log10(y)~log10(x)))

# Plot the ggplot version
dev.set(dev2)
ggplot(mydata) + aes(x=x, y=y) + scale_x_log10() + scale_y_log10() +
stat_density2d(geom="tile", aes(fill=..density..^0.25), contour=FALSE) +
scale_fill_gradientn(colours = colorRampPalette(c("white", blues9))(256))

请注意,在基本图形版本中,100 个最“稀疏”的点是如何绘制在平滑密度图上的。稀疏度由点坐标处的核密度估计值定义,重要的是,核密度估计是在对数变换(或任何其他坐标变换)之后计算的。我可以通过添加 + geom_point(size=0.5) 来绘制所有点,但我只想要稀疏的点。

有什么办法可以用 ggplot 来完成这个任务吗?这实际上有两个部分。第一个是找出坐标变换后的异常值,第二个是仅绘制这些点。

最佳答案

这是一种解决方法!它不适用于密度最小的 n 个点,但会绘制密度^0.25 小于 x 的所有点。

它实际上绘制了 stat_密度2d() 图层,然后是 geom_point(),然后是 stat_desired2d(),使用 alpha 创建透明最后一层中间的“洞”,密度^0.25 高于(在本例中)0.4。

显然,运行三个图会对性能产生影响。

# Plot the ggplot version
ggplot(mydata) + aes(x=x, y=y) + scale_x_log10() + scale_y_log10() +
stat_density2d(geom="tile", aes(fill=..density..^0.25, alpha=1), contour=FALSE) +
geom_point(size=0.5) +
stat_density2d(geom="tile", aes(fill=..density..^0.25, alpha=ifelse(..density..^0.25<0.4,0,1)), contour=FALSE) +
scale_fill_gradientn(colours = colorRampPalette(c("white", blues9))(256))

enter image description here

关于r - 如何在 ggplot 中重现 smoothScatter 的离群值绘图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13094827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com