How to reproduce smoothScatter's outlier plott

2019-08-02 00:17发布

我试图得到类似的东西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做到这一点? 实际上有两个环节进行。 首先是要弄清楚什么异常值的坐标转换,第二个是唯一的绘制这些点。

Answer 1:

这里有各种各样的解决方法! 是不上密度最小的n个点的工作,但情节都带有密度^ 0.25小于x点。

它实际上绘出stat_density2d()层,则geom_point(stat_density2d()使用的α,以在最后一层的中间的透明的“孔”,其中密度^ 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))



文章来源: How to reproduce smoothScatter's outlier plotting in ggplot?