You've successfully subscribed to MyPad Blog
Great! Next, complete checkout for full access to MyPad Blog
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Beautifying a ggplot with ggpattern

Beautifying a ggplot with ggpattern

Just discovered this pretty cool library called ggpattern. It helps in adding custom patterns to your ggplot images.

Here is a quick example of its usage along with some gganimate pizzaz.

# credit: https://coolbutuseless.github.io/package/ggpattern/articles/gganimate.html

library(gganimate)

# install.packages("remotes")
# remotes::install_github("coolbutuseless/ggpattern")
library(ggpattern)

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Create a dataset with 2 different states
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
df1 <- data.frame(time = 1, offset = 0    , trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2), stringsAsFactors = FALSE)
df2 <- data.frame(time = 2, offset = 0.045, trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2), stringsAsFactors = FALSE)
df  <- rbind(df1, df2)

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Plot the two different states and transition between them.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
p <- ggplot(df, aes(trt, outcome)) +
  geom_col_pattern(
    aes(
      pattern_fill    = trt,
      pattern_xoffset = I(offset),
      pattern_yoffset = I(-offset)
    ),
    colour          = 'black',
    fill            = 'white',
    pattern_density = 0.5,
    pattern_angle   = 45
  ) +
  theme_bw() +
  labs(title = "ggpattern + gganimate") +
  theme(legend.position = 'none') +
  coord_fixed(ratio = 1/2)

p <- p + transition_states(time, transition_length = 2,
                    state_length = 0, wrap = FALSE)

animate(p, nframes = 60, fps = 20)

anim_save(file="ggpattern + gganimate.gif", animation = last_animation(), path=".")

Lots of more examples here