AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 78916299
Accepted
bill999
bill999
Asked: 2024-08-27 05:06:32 +0800 CST2024-08-27 05:06:32 +0800 CST 2024-08-27 05:06:32 +0800 CST

如何精确叠加两个图

  • 772

作为起点,我使用 Kat 对这个问题的回答(如何使地图边框的粗糙度小于地图填充的粗糙度)中非常有用的代码来创建两个图表,目的是将其中一个图表放在另一个图表之上。

library(magrittr)
library(ggplot2)
#devtools::install_github("xvrdm/ggrough")
library(ggrough)
library(sf)
library(htmltools)    
library(ggiraph)      

trace(ggrough:::parse_rough, edit=TRUE)
#In the popup window, paste this so that parse_rough will use parse_sf for GeomSf.
function (svg, geom) 
{
  rough_els <- list()
  if (geom %in% c("GeomCol", "GeomBar", "GeomTile", 
                  "Background")) {
    rough_els <- append(rough_els, parse_rects(svg))
  }
  if (geom %in% c("GeomArea", "GeomViolin", "GeomSmooth", 
                  "Background")) {
    rough_els <- append(rough_els, parse_areas(svg))
  }
  if (geom %in% c("GeomPoint", "GeomJitter", "GeomDotPlot", 
                  "Background")) {
    rough_els <- append(rough_els, parse_circles(svg))
  }
  if (geom %in% c("GeomLine", "GeomSmooth", "Background")) {
    rough_els <- append(rough_els, parse_lines(svg))
  }
  if (geom %in% c("Background")) {
    rough_els <- append(rough_els, parse_texts(svg))
  }
  if (geom %in% c("GeomSf")) {
    rough_els <- append(rough_els, parse_sf(svg))
  }
  purrr::map(rough_els, ~purrr::list_modify(.x, geom = geom))
}

# Create the function parse_sf.
parse_sf <- function (svg) {
  shape <- "path"
  keys <- NULL
  ggrough:::parse_shape(svg, shape, keys) %>% {
    purrr::map(., 
               ~purrr::list_modify(.x, 
                                   points = .x$d, 
                                   shape = "path"
               ))
  }
}
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)

b <- ggplot(nc) + geom_sf(color = "black") + theme_minimal() +
  theme(panel.grid = element_line(color = NA),  # not resized or removed! (keep spacing)
        axis.text = element_text(color = NA))

options <- list(GeomSf = list(fill_style = "hachure", angle = 60, angle_noise = 1,
                              gap_noise = 0, gap = 6, fill_weight = 2, bowing = 5,
                              roughness = 30))

(xx <- get_rough_chart(b, options))  # from your question
fixer <- function(ggr) {          # where ggr is the ggrough graph
  nd <- lapply(1:length(ggr$x$data), function(j) {
    if(!is.null(ggr$x$data[[j]]$lengthAdjust)) { # if a text element (axis label)
      ggr$x$data[[j]]$content <- ""              # remove text, but keep spacing
      ggr$x$data[[j]]                            # return modified data element
    } else {
      ggr$x$data[[j]]                            # not text, return orig data
    }
  })
  ggr$x$data <- nd                               # add mod data to graph
  ggr                                            # return mod graph
}
xx2 <- xx %>% fixer()  # modify the plot, to hide text

(g2 <- ggplot(nc) +
    geom_sf(fill = "transparent", color = "black", linewidth = 2) +
    theme_minimal() +
    theme(plot.background = element_rect(fill = NA, color = "transparent"), # no white background
          panel.background = element_rect(fill = NA, color = "transparent"),
          text = element_text(size = 9)))      # text size to match defaults in ggrough

gg <- girafe(ggobj = g2, width_svg = 7, height_svg = 5)  # h/w default w/ ggrough

browsable(div( # parent div, size matches ggrough's default
  style = css(width = "960px", height = "500px", position = "relative"),
  div(xx2, style = css(display = "block")),                           # ggrough graph
  div(gg, style = css(position = "absolute", top = 0, padding.top = "54.2px", # layer behind
                      width = "610px", height = "500px", z.index = -2))
              )) # size and padding found by trial and error with defaults for graph sizes

答案中的图表似乎已正确叠加。但是,当我运行相同的代码(在 RStudio 中)时,我得到的叠加是不正确的:

在此处输入图片描述

我也在另一台计算机上的 RStudio 上尝试过,也得到了不完美的叠加,但程度不同。

我有两个问题:

  1. 如何才能正确地叠加图形,而不必反复试验?
  2. 我该如何调整代码,以便将当前背景切换到前景?换句话说,我该如何让黑色边框位于灰色涂鸦之上,而不是相反?我尝试div在结尾处交换两个边框的顺序,但没有成功。
  • 1 1 个回答
  • 58 Views

1 个回答

  • Voted
  1. Best Answer
    Kat
    2024-08-28T05:55:37+08:002024-08-28T05:55:37+08:00

    我找不到关于如何ggrough转换为文字大小的明确信息。

    在这个答案中,我使用了 7 x 5 (英寸) 的宽高比,这是相当标准的 ( browser、knitr等等)。我没有测试这些公式是否适用于不同的宽高比。

    因为我无法确定什么看起来像是向吊扇上扔泥巴ggrough,所以我建立了数百个图表,对它们进行对齐,然后确定是否存在我可以创建的公式来准确地识别 ggplot 对象的正确尺寸。

    当我提到时,ggplot我指的是位于顶部的边框层。当我提到时,ggrough我指的是位于底部的填充层。

    以下指标根据分配给 ggrough 的高度和宽度而变化。

    • ggplot 的宽度
    • ggplot 的顶部填充
    • ggplot 的字体大小
    • 左填充

    由于这些元素分散在不同的函数中,我创建了一个依赖于 3 个输入的 UDF:ggrough 的宽度和高度以及要绘制的数据。

    您为宽度和高度指定的值...我相信这些值代表英寸,但我不会假设 1 = 1 英寸。他们的文档中没有任何内容表明这些值代表什么,但 1 相当于大约 72 像素,如果 1 代表一英寸,那么这是准确的。

    函数中写入了 2 个错误捕获调用。1) 如果高度超过宽度:这只会在 ggrough 上方创建更多无用的空白。2) 如果给定的高度/宽度值超过浏览器窗口大小。(如果是这样,ggrough 图会失去其纵横比并隐藏部分图 - 没什么好处!)如果您触发其中任何一个,您将在控制台中看到一条消息,让您知道发生了什么。

    我在代码中留下了一条用于验证的消息,因为您可能会发现它是有用的信息。它在处理数据时会将所有计算出的指标吐出到控制台中。

    aligner <- function(grw, grh, nc) {   # set rough chart width/height (8, 5, for example), data used in plot
      if(isTRUE(grh > grw)) {
        return(cat("\033[0;37;101mThe height should not exceed the width for this plot.\033[0m\n"))
      }
             # hide the text in the ggrough object 
      fixer <- function(ggr) {                         # where ggr is the ggrough graph
        nd <- lapply(1:length(ggr$x$data), function(j) {
          if(!is.null(ggr$x$data[[j]]$lengthAdjust)) { # if a text element (axis label)
            ggr$x$data[[j]]$content <- ""              # remove text, but keep spacing
            ggr$x$data[[j]]                            # return modified data element
          } else {
            ggr$x$data[[j]]                            # not text, return orig data
          }
        })
        ggr$x$data <- nd                               # add mod data to graph
        ggr                                            # return mod graph
      }
      tpad <- function(grw, grh) {   # calculate the top padding, given ggrough width, height
        delta <- grh - grw + 1
        widD <<- 8 - grw
        widH <- 7 - grh
        45.5 - widD * 10.0 + delta * 35.5 + .5
      }
      #---------- set the variables -----------
      pltW = 7; pltH = 5            # setting aspect ratio; if this changes nothing else may work correctly!
      browsW = 960                  # browser width (default is 960) for htmlwidgets/ used for error checking
      browsH = 500                  # browser height (default is 500) for htmlwidgets/ used for error checking
      
      sfs <- list(-0.325, 6.1)      # slope formula metrics for calculating font size of ggplot object
      sdw <- list(72.5, -3)         # slope formula metrics for calculating width of div
      
      #---------- calculate metrics -----------
      fs <- sfs[[1]] * grw + sfs[[2]]        # calculate the approriate font size for ggplot object
      dw <- sdw[[1]] * grw + sdw[[2]]        # calculate the approriate div width for ggplot object
      
      if(any(pltH/pltW * dw > browsH)) {     # validate aspect ratio by width fits in browser window
        return(cat("\033[0;37;101mWidth of", grw, "is too high to fit. Reduce width & try again.\033[0m\n"))
      } 
      
      tp <- tpad(grw, grh)                   # calculate top padding 
      if(isTRUE(tp < 0)) {                   # validate aspect ratio fits in browser window
        return(cat("\033[0;37;101mWith the given height and width, the plot doesn't fit. Try increasing the height.\033[0m\n"))
      } 
      
      lp <- ifelse(isTRUE(widD > 0), 1 - .5 * widD, 1)  # calculate the left padding
      
      #------------ create graphs ------------
      b <- ggplot(nc) + geom_sf(color = "black") + theme_minimal() +
        theme(panel.grid = element_line(color = NA),  # not resized or removed! (keep spacing)
              axis.text = element_text(color = NA))
      
      options <- list(GeomSf = list(fill_style = "hachure", angle = 60, angle_noise = 1,
                                    gap_noise = 0, gap = 6, fill_weight = 2, bowing = 5,
                                    roughness = 30))
      xx <- get_rough_chart(b, options, width = grw, height = grh) %>% fixer() # create gg rough graph
      
      g2 <- ggplot(nc) +
        geom_sf(fill = "transparent", color = "black", linewidth = 2) +
        theme_minimal() +
        theme(plot.background = element_rect(fill = NA, color = "transparent"), # no white background
              panel.background = element_rect(fill = NA, color = "transparent"),
              text = element_text(size = rel(fs)))      # text size to match defaults in ggrough
      
      gg <- girafe(ggobj = g2, width_svg = pltW, height_svg = pltH)  # great ggplot graph HTML
      
      #-------- notify user of calcs ---------
      message(paste0("Entered size: ", grw, ", ", grh, "; calculated dims are: ", 
                     "div width ", dw, "; font size ", fs, "; top padding ", tp, 
                     " and left padding ", lp))
      
      #-------- create graph overlay ---------
      browsable(div(                                # parent div, size matches ggrough's default
        style = css(width = "960px", height = paste0(browsH, "pt"), position = "relative"),
        div(xx, style = css(display = "block", padding.left = paste0(lp, "px"))), # ggrough graph
        div(gg, style = css(position = "absolute", top = 0,                       # ggplot graph
                            padding.top = paste0(tp, "px"), 
                            width = paste0(dw, "px"), z.index = -2))
      ))
    }
    
    aligner(7, 7, nc)
    

    7点,7点

    虽然 SO 自然会将图像尺寸最大化以适应,但您至少可以看到字体大小的变化。

    或者在 5, 5 处:

    5点,5点

    或者在9点、7点:

    9、7

    这是您可能看到的输出暗淡和错误消息的示例。

    错误消息

    • 1

相关问题

  • 将复制活动的序列号添加到 Blob

  • Packer 动态源重复工件

  • 选择每组连续 1 的行

  • 图形 API 调用列表 subscribedSkus 状态权限不足,但已授予权限

  • 根据列值创建单独的 DF 的函数

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve