ggplot2 2D密度图 - 渐变填充过于平滑

时间:2018-04-18 13:13:20

标签: r ggplot2 scatter-plot density-plot

我对ggplot2包和渐变填充有一些困难。对于数据点数较少的数据,其梯度和密度强度并不匹配。以下是一个示例:enter image description here

我使用的代码是:

pt <- read.xlsx("plots.xlsx", sheetName = "PT1_TB varseq", stringsAsFactors=FALSE)

ggplot(pt, aes(x=pt$BAF, y=pt$LogR) ) + 
  stat_density_2d(aes(fill = ..density..), geom = "raster", contour = FALSE) +
  scale_fill_distiller(palette= "Spectral", direction=-1) +
  scale_y_continuous(name="LogR", limits = c(-0.8, 0.6), breaks = seq(-0.8, 0.6, 0.2)) +
  scale_x_continuous(name="BAF", breaks = seq(0, 0.8, 0.2)) +
  theme(
    legend.position='none',
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    axis.line = element_line(colour = "black")
  ) +
  geom_point(aes(shape = factor("cyl")), size = 1) + scale_shape(solid = FALSE)

我希望渐变更突然地改变,例如,我希望在(0; 0.2)和(0.25; -0.2)之间的点之间看到更多的颜色分离。此外,没有点的中间的黄色应该是蓝色。

在我看来,有人知道如何消除轴与实际情节之间的白色差距吗?

提前致谢:)

1 个答案:

答案 0 :(得分:5)

如果您能提供可重复的示例,将会有所帮助。但是,为了推动@RichardTelford主页评论的重点,这里有一个利用manipulate包来交互式设置h带宽参数的示例,此外还有n - 网格点数。

library(ggplot2)
library(manipulate)

manipulate(
  ggplot(faithful, aes(x = eruptions, y = waiting)) +
    geom_point() +
    xlim(0.5, 6) +
    ylim(40, 110) +
    stat_density_2d(geom = "raster", aes(fill = ..density..), contour = F, 
                    h = c(x_bandwidth, y_bandwidth),
                    n = grid_points) +
    scale_fill_distiller(palette = "Spectral", direction = -1),
  x_bandwidth = slider(0.1, 20, 1, step = 0.1),
  y_bandwidth = slider(0.1, 20, 1, step = 0.1),
  grid_points = slider(1, 100, 16)
)

所以我们的普通香草(默认)情节如下所示:

Plot 1

我们可以使用齿轮图标中的弹出菜单以交互方式更改参数:

Plot 2

Plot 3