如何在ggplot中重现smoothScatter的异常值绘图?

Rya*_*son 12 r smooth scatter-plot ggplot2

我试图获得类似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))
Run Code Online (Sandbox Code Playgroud)

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

有没有办法用ggplot来实现这个目标?这有两个部分.第一个是找出坐标变换的异常值,第二个是仅绘制那些点.

Tro*_*roy 13

这是一种解决方法!是不是在最不密集的n点上工作,而是绘制密度小于0.25的所有点.

它实际上绘出了stat_density2d()层,那么geom_point(,那么stat_density2d(),使用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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述