ggplot2 2D密度图-渐变填充太平滑 [英] ggplot2 2D Density plot - the gradient fill is too smooth

查看:303
本文介绍了ggplot2 2D密度图-渐变填充太平滑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用ggplot2软件包和渐变填充时遇到了一些困难.对于我的数据点数量少的数据,其梯度和密度强度实际上并不匹配.这是一个示例:

I am having some difficulty with the ggplot2 package and the gradient fill. For my data with low number of data points, its gradient and density intensity doesn't really match. Here is an example:

我正在使用的代码是:

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)点之间的颜色分离更大.此外,中间没有点的黄色应该是蓝色.

I would like the gradient to change more abruptly, for example, I would like to see more seperation in colors between points at (0;0.2) and (0.25;-0.2). Furthermore the yellow color in the middle where no points are should be blue.

虽然我在做,但是有人知道如何消除轴和实际图之间的白色间隙吗?

While I am at it, does anybody know how remove the white gap between the axes and the actual plot?

先谢谢您了:)

推荐答案

如果您可以提供可复制的示例,则将有所帮助.但是,为了通过@RichardTelford主页发表评论,这里是一个示例,该示例除了n(网格点的数量)之外,还利用manipulate包以交互方式设置h带宽参数.

It would help if you could provide a reproducible example. However, to drive the point in the comment by @RichardTelford home, here's an example which leverages the manipulate package to interactively set the h bandwidth parameters, in addition to n -- the number of grid points.

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)
)

因此,我们的普通香草(默认)图如下所示:

So our plain-vanilla (default) plot looks like this:

我们可以使用齿轮图标访问的弹出菜单来交互式地更改参数:

We can interactively change the parameters using the pop-up menu accessible from the gear icon:

这篇关于ggplot2 2D密度图-渐变填充太平滑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆