rggplot2ggpattern

How to use a dominant fill color in geom_col_pattern when 2 colors are used?


In the following example, I want the "#1E466E" color to take about 90% of bar length. So, I tried using pattern_gravity as "right" or "left" but that does not make any difference. Please guide me how I can make one color dominant. Currently, both colors seem to be taking 50% of the bar length.

library(ggplot2)
library(ggpattern)
df <- data.frame(level = c("a", "b", "c", 'd'), outcome = c(2.3, 1.9, 3.2, 1))
gg <- ggplot(df) +
  geom_col_pattern(
    aes(outcome, level),
    pattern = 'gradient',
    pattern_fill = "#1E466E",       
    pattern_fill2 = "#00A8E8",
    pattern_orientation = "horizontal",
    pattern_gravity = 'right'
  ) +
  theme_bw(18) +
  theme(legend.position = 'none')
plot(gg)

enter image description here


Solution

  • Since R v4.1.0, you don't need to use ggpattern to create a gradient fill in ggplot2. You can do it directly by passing a grid::linearGradient as the fill colour of the bars. Furthermore, it gives a bit more control. In the following example, I have set the first 60% of the bar to be dark blue, the final 10% of the bar to be light blue and the gradient to occur in between these two regions:

    library(ggplot2)
    
    df <- data.frame(level = c("a", "b", "c", 'd'), outcome = c(2.3, 1.9, 3.2, 1))
    
    ggplot(df, aes(outcome, level)) +
      geom_col(fill = grid::linearGradient(rep(c("#1E466E", "#00A8E8"), each = 2),
                                           stops = c(0, 0.6, 0.9, 1), group = FALSE,
                                           x1 = 0, y1 = 0.5, x2 = 1, y2 = 0.5)) +
      theme_bw(18) +
      theme(legend.position = 'none')
    

    enter image description here

    If you just want the gradient happening in the last 10% of the bars, you could change the stops argument in the above code to stops = c(0, 0.9, 0.99, 1), which gives you

    enter image description here