r - 调整 geom_tile 大小以消除边距效应

标签 r ggplot2

我正在尝试可视化各种随机采样方法,这些方法严格在单位正方形内生成(x,y)[0,1]x[0,1]。我的想法是通过将正方形分成更小的正方形并计算每个正方形内的点数来展示均匀性属性。我将这些计数存储在不同大小的矩阵中,例如

cells1 <- structure(c(0, 1, 0, 0, 1, 0, 2, 3, 1, 1, 0, 1, 0, 0, 2, 0, 2, 
0, 1, 1, 2, 1, 0, 0, 3, 1, 2, 1, 1, 1, 0, 1, 3, 2, 2, 1, 1, 2, 
0, 0, 0, 1, 0, 2, 1, 3, 0, 0, 1, 1, 2, 1, 1, 2, 1, 0, 1, 0, 2, 
0, 0, 0, 3, 1, 1, 2, 0, 0, 1, 2, 0, 1, 0, 0, 1, 3, 0, 3, 3, 1, 
1, 0, 0, 0, 0, 1, 1, 2, 0, 3, 0, 2, 0, 1, 1, 3, 4, 0, 1, 5, 1, 
1, 1, 0, 0, 5, 0, 4, 2, 0, 0, 1, 1, 2, 0, 1, 3, 1, 0, 3, 2, 0, 
1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 2, 1, 3, 1, 0, 0, 
2, 2, 1, 1, 0, 2, 1, 1, 2, 0, 1, 0, 2, 1, 0, 0, 2, 0, 0, 0, 0, 
1, 0, 0, 1, 1, 2, 1, 2, 1, 1, 2, 0, 3, 1, 2, 1, 0, 0, 1, 1, 1, 
1, 2, 1, 0, 1, 1, 0, 1, 1, 0, 0, 2, 1, 1, 1, 1, 1, 4, 1, 0, 0, 
0, 1, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 2, 1, 3, 0, 1, 3, 0, 0, 0, 
1, 3, 1, 0, 1, 1, 1, 2, 1, 2, 2, 1, 1, 2, 0, 0, 1, 2, 0, 1, 2, 
1, 2, 1, 0, 0, 1, 1, 2), .Dim = c(16L, 16L))

cells2 <- structure(c(16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 16, 16, 16, 
15, 16, 16), .Dim = c(4L, 4L))

自然地,我想到了geom_tile,我当前的代码如下。

plot_step <- function(cells, filename = NULL) {
  library(ggplot2)
  library(reshape2)
  plot_data <- melt(cells, varnames = c("x", "y"))
  # transform from index to tile position
  plot_data$x <- (plot_data$x - 1) / max(plot_data$x - 1)
  plot_data$y <- (plot_data$y - 1) / max(plot_data$y - 1)
  ggplot(plot_data, aes(x, y, fill = value)) +
    geom_tile() +
    geom_text(aes(label = value)) +
    theme_bw() +
    scale_fill_gradient(low="white", high="red") +
    guides(fill = FALSE)
}

plot_step(cells1); plot_step(cells2)

enter image description here

enter image description here

除了小问题之外,这几乎是我想要的。理想情况下,注释的变换和图 block 大小结合起来应该生成精确覆​​盖整个单位正方形的图像,而不会低于零或高于单位。

我用我出色的手绘技巧在第二张图片中突出显示了所需的边距。我对一种适用于不同尺寸的通用解决方案感兴趣(例如,cells1cells2 的悬挂方式不同)。这可能是对 geom_tile 进行轻微的数据转换或进行一些调整,或者两者兼而有之。

非常感谢任何帮助!

最佳答案

图 block 始终位于其质心处。解决方案是计算每个轴的一组中断和标签。

n.x <- length(unique(plot_data$x))
x.breaks <- seq(-nx / 2, 1 + nx/2, length = 5)
x.labels <- seq(0, 1, length = 5)
scale_x_continuous(breaks = x.breaks, labels = x.label)

您可能还想添加coord_fixed()。它会给你方形瓷砖。

关于r - 调整 geom_tile 大小以消除边距效应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33101550/

相关文章:

r - 如何标注特定区间的密度图曲线下面积?

r - 从 R 中保存的绘图创建视频

r - 如何在R中返回每组行?

R计算数据帧每一行中的字符串变量

r - 针对长数据框的所有组的散点图

r - 以编程方式在 ggplot 中使用 facets 设置轴面

r - ggplot geom_text 带有可变标签的注释

r - 从 geom_smooth() 中提取多条趋势线的斜率

R ggplot : specify aes by index

r - ggplot : Plotting the bins on x-axis and the average on y-axis