[英]Adding visual embellishment in a custom ggplot theme
我會在這里使用grid::linesGrob
來使用annotation_custom
。 這允許您相對於面板放置線,而不必使用 plot 限制,這會產生不一致的結果。 它還允許線條延伸到繪圖區域的左右界限之外。
假設您的 plot 創建有點像這樣:
library(ggplot2)
p <- ggplot(mpg, aes(displ, hwy, col = class)) +
geom_point() +
labs(title = "Test 1, theme 1", subtitle = "R default dataset",
caption = "Organization caption here",
y = "Fuel efficiency (mpg)",
x = "Engine displacement (litres)") +
scale_color_brewer(palette = "Set2", name = NULL) +
theme(panel.grid = element_line(color = "gray50"),
panel.border = element_rect(fill = NA),
legend.position = "top")
p
要添加該行,您可以執行以下操作:
p + coord_cartesian(clip = "off") +
annotation_custom(grid::linesGrob(
x = unit(c(-1, 2), "npc"), y = unit(c(1.2, 1.2), "npc"),
gp = grid::gpar(col = "orange2", lwd = 5)))
如果沒有可重現的示例,這有點困難,但是您可以使用帶有“段”的annotate
,並使用Inf
定義 x 值,使用max(y)
+ 一些值定義 x 值,具體取決於您的theme
布局,如下所示:
library(ggplot2)
library(dplyr)
mtcars %>%
ggplot(aes(x = mpg, y = wt)) +
geom_point() +
annotate("segment", x = -Inf, xend = Inf, y = max(mtcars$wt) + 0.5, yend = max(mtcars$wt) + 0.5, colour = "orange", size = 2) +
coord_cartesian(clip = "off", ylim = c(min(mtcars$wt), max(mtcars$wt))) +
theme(plot.margin = unit(c(3,3,1,1), "lines"))
由代表 package (v2.0.1) 於 2022 年 7 月 27 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.