[英]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.