Home > other >  Define color and radius of the background in shadowtext::element_shadowtext
Define color and radius of the background in shadowtext::element_shadowtext

Time:06-11

Shadowtext allows to set the bg.color as well as the bg.r. However, I'm missing that option when using element_shadowtext. Is there a way to overcome that? I'm open to using other packages/ approaches. Unfortunately ggtext does not allow to specify a textbox around axis labels.

data <- data.frame(ID= c("A", "B", "C"), Value =c(1.5,2,1.75))

library(ggplot2)
library(shadowtext)
ggplot(data, aes(x=ID, y=Value))   
  geom_col()   
  theme(axis.text.x=shadowtext::element_shadowtext(color="white"),
        axis.title.x = element_blank()) 
  shadowtext::geom_shadowtext(aes(label=Value), 
                              y=1, hjust=0.5,
                              bg.color="white", bg.r=0.2, color = "black")

enter image description here

CodePudding user response:

I think one can achieve a nicer shadow effect using with_shadow from ggfx. Unforunately, it requires a bit more work to get the effect on axis elements. The radius is controlled by sigma and the color by the colour argument.

library(ggplot2)
library(ggfx)

p <- ggplot(data, aes(x = ID, y = Value))   
  geom_col()   
  lapply(1:10, function(x) {
  with_shadow(colour = 'white', x_offset = 0, y_offset = 0, sigma = 3,
    geom_text(aes(label = Value), y = 1, hjust = 0.5)
  )})  
  theme(axis.text.x = element_text(color = 'white'),
        axis.title.x = element_blank())

p2 <- ggplot_gtable(ggplot_build(p))

p2$grobs[[7]]$children$axis$grobs[[2]]$children[[1]] <-
  do.call(grid::gList, lapply(1:10, function(x) {
  with_shadow(
    p2$grobs[[7]]$children$axis$grobs[[2]]$children[[1]],
    x_offset = 0, y_offset = 0, sigma = 5)
  }))

grid::grid.newpage()
grid::grid.draw(p2)

enter image description here

CodePudding user response:

Whilst the solution by @Allan is very powerful, to me, the annotate-solution seems to be doing the job (thanks to @tjebo and enter image description here

and works even for polar plots, even though I don't know how to limit the y-axis while adding the labels, as clip = 'off' in coord_polar does not seem to allow the annotation outside of the scale.

ggplot(data, aes(x = ID, y = Value))   
  geom_col()  
  shadowtext::geom_shadowtext(aes(label=Value), 
                              y=1, hjust=0.5,
                              bg.color="white", bg.r=0.2, color = "black") 
  theme(axis.text.x = element_blank(),
        axis.title.x = element_blank()) 
  annotate("shadowText", x = c("A", "B", "C"), y = 2.1, label = c("A", "B", "C"), color="black", bg.color="grey", bg.r=0.2, fontface="bold") 
  coord_polar()

enter image description here

  • Related