【问题标题】:Adding Logo to R plot dynamically将徽标动态添加到 R 绘图
【发布时间】:2021-10-25 02:12:13
【问题描述】:
library(dagitty)
library(ggplot2)
library(ggdag)

get_jpg <- function(filename) {
  grid::rasterGrob(jpeg::readJPEG(filename), interpolate = TRUE)
    }
logo <- get_jpg("logo.jpg")

ex.1 <- dagitty("dag { 

X <- A -> B <- C -> Y
X <- B -> Y
X -> W -> Y
S-> T -> C
}")

exposures(ex.1) <- 'X'
outcomes(ex.1) <- 'Y'

tidy.1 <- ex.1 %>% 
  tidy_dagitty() %>%
  mutate(label = str_to_upper(name)) 


ggdag(tidy.1 , text = FALSE, use_labels = "label") + theme_dag() +
  theme_light() +
  annotation_custom(logo, xmin = 6.5, xmax = 8.5, ymin = -5, ymax = -8.5) +
  coord_cartesian(clip = "off") +
  theme(plot.margin = unit(c(1, 1, 3, 1), "lines"))

我有这段代码可以在我的情节中放置一张 JPG 图像。我了解 xmin、xmax、ymin ymax 坐标未对齐。有没有办法可以在图表的右下角显示图像(类似于此处显示的图像:https://www.markhw.com/blog/logos)?如果可能,我想在不指定坐标的情况下动态地执行此操作,因为我不确定 ggdag 如何为因果图绘制 x 和 y 坐标。

谢谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    实现所需结果的一种方法是通过rasterGrob 而不是annotation_cutom 设置坐标来定位徽标。利用您在下面我的代码中链接的帖子中的示例代码,我将 R 徽标放在右下角。从我添加的两个示例中可以看出,这与数据范围无关,并且将始终将徽标放在同一位置:

    library(tidyverse)
    
    download.file("https://www.r-project.org/logo/Rlogo.png", "logo.png")
    
    get_png <- function(filename, x = unit(0.5, "npc"), y= unit(0.5, "npc"), 
                        width = NULL, height = NULL, gp = grid::gpar()) {
      grid::rasterGrob(png::readPNG(filename), interpolate = TRUE,
                       x = x, y = y, width = width, height = height, gp = gp)
    }
    
    species <- starwars %>% 
        count(species) %>% 
        filter(!is.na(species) & n > 1) %>% 
        arrange(-n) %>% 
        mutate(species = factor(species, species))
    
    width = 3
    l <- get_png("logo.png", 
                 x = unit(1, "npc") - unit(width / 2, "lines"), 
                 y = unit(-width, "lines"), 
                 width = unit(width, "lines"))
    
    p_fun <- function(x, width = 3) {
      ggplot(x, aes(x = species, y = n)) +
        geom_bar(stat = "identity") +
        coord_cartesian(clip = "off") +
        theme_light() +
        theme(plot.margin = unit(c(1, 1, width, 1), "lines"))
    }
    
    p_fun(species) +
      annotation_custom(l)
    

    p_fun(filter(species, n > 2)) +
      annotation_custom(l)
    

    【讨论】:

    • 谢谢! gp 参数到底是什么?
    • 噢。忘记放下它,因为它实际上是不需要的。但在更一般的情况下,您可以通过 grob 的 gp 参数传递额外的图形参数(参见?grid::gpar),例如在文本 grob 的情况下,这就是您设置字体颜色或大小的方式。但实际上不确定 rasterGrob 是否有任何额外的 gp。
    猜你喜欢
    • 2017-12-16
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    相关资源
    最近更新 更多