繁体   English   中英

在自定义 ggplot 主题中添加视觉装饰

[英]Adding visual embellishment in a custom ggplot theme

我目前正在为我的组织中使用的自定义 ggplot 主题制作原型。 目前,主题看起来像这样(使用 mtcars 数据): 在此处输入图像描述

我想添加一个单色条(以组织的原色),在图表标题区域下划线,作为一种易于扩展的品牌类型(而不是限制图表纵横比和大小的 jpeg 徽标)。 我制作了我试图在绘画中实现的效果的模型:

在此处输入图像描述

我知道 annotate() 但据我了解 function 只接受 arguments 对应于绘图区域中的 x 和 y 坐标,所以我不知道如何创建绑定到外部点的注释绘图区

我会在这里使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM