我有一个df,其中包含创建正方形的坐标:

library(ggplot2)

df = data.frame(xmin = 1, xmax = 3, ymin = 10, ymax = 15)

ggplot(df) +
        geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), fill = "green")

enter image description here

现在,我想有一个函数,当它被赋予df时,它会在df上添加新行,有5个原始正方形的zoom 版本,如下所示:

enter image description here

这意味着,新正方形中绿色正方形的面积相当于原始正方形的5/9.

我还想递归地制作它,这样,考虑到df的zoom 版本(5个正方形,如第二幅图),它给出:

enter image description here

等等

推荐答案

使用递归方法,您可以执行以下操作:

square5 <- function(xmin, xmax, ymin, ymax) {
  x <- data.frame(
    xmin = c(0, rep(1/3, 3), 2/3),
    xmax = c(0, rep(1/3, 3), 2/3) + 1/ 3,
    ymin = c(1/3, 0, 1/3, 2/3, 1/3),
    ymax = c(1/3, 0, 1/3, 2/3, 1/3) + 1/ 3
  )
  
  x[c("xmin", "xmax")] <- lapply(x[c("xmin", "xmax")], scales::rescale, to = c(xmin, xmax), from = c(0, 1))
  x[c("ymin", "ymax")] <- lapply(x[c("ymin", "ymax")], scales::rescale, to = c(ymin, ymax), from = c(0, 1))
  
  return(x)
}

df = data.frame(xmin = 1, xmax = 3, ymin = 10, ymax = 15)

df1 <- purrr::reduce(seq(5), function(x, n) purrr::pmap_df(x, square5), .init = df)

library(ggplot2)

ggplot(df1) +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), fill = "green", color = "darkgreen", size = .5)

R相关问答推荐

提取R中值和列名的所有可能组合

无法运行通过R中的Auto.arima获得的ARIMA模型

ggplot 2中的地块底图(basemaps_gglayer()不起作用)

如何将在HW上运行的R中的消息(错误、警告等)作为批处理任务输出

查找图下的面积

使用gggrassure减少地块之间的空间

如何根据嵌套元素的名称高效而优雅地确定它属于哪个列表?

如何调整曲线图中的y轴标签?

如何从像glm这样的模型中提取系数表的相关性?

将重复项转换为NA

以NA为通配符的R中的FULL_JOIN以匹配其他数据中的任何值.Frame

条形图顶部与其错误条形图不对齐

将摘要图添加到facet_WRAP gglot的末尾

在R中的数据框上使用Apply()函数时,如何保留非数字列?

在散点图中使用geom_point放置线图例

自定义交互作用图的标签

如果满足条件,则替换列的前一个值和后续值

如何修改GT表中组名行的 colored颜色 ?

在shiny 表格中输入的文本在第一次后未更新

当y为负值时,无法使stat_cor正确定位到底部?