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 坐標。
謝謝!
uj5u.com熱心網友回復:
實作所需結果的一種選擇是通過設定坐標 viarasterGrob而不是 via來定位徽標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)

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/338261.html
