Home > Net >  Adding visual embellishment in a custom ggplot theme
Adding visual embellishment in a custom ggplot theme

Time:07-28

I'm currently prototyping custom ggplot themes for use within my organisation. Currently, the theme looks like this (using mtcars data): enter image description here

I would like to add a solid-colored bar (in the org's primary color) underlining the chart title region to act as an easily scalable type of branding (rather than a jpeg logo which restricts the aspect ratio and size of the charts). I made a mockup of the effect I'm trying to achieve in paint:

enter image description here

I'm aware of annotate() but as far as I understand it that function only accepts arguments corresponding to x and y coordinates in the plotting area, so I don't know how to create an annotation that is bound to a point outside of the plotting area

CodePudding user response:

I would use annotation_custom using a grid::linesGrob here. This allows you to place the line relative to the panel without having to use the plot limits, which can produce inconsistent results. It also allows the line to extend beyond the left and right limits of the plotting area.

Suppose your plot is created a bit like this:

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

enter image description here

To add the line you can do:

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)))

enter image description here

CodePudding user response:

It is a bit hard without reproducible example, but you can use annotate with "segment" and define the x-values with Inf and the y-values with max(y) some value depending on your theme layout like this:

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")) 

Created on 2022-07-27 by the reprex package (v2.0.1)

  • Related