簡體   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