How to add texture to fill colors in ggplot2

前端 未结 8 1215
误落风尘
误落风尘 2020-11-22 08:30

I\'m currently using scale_brewer() for fill and these look beautiful in color (on screen and via color printer) but print relatively uniformly as greys when us

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 09:14

    I've just discovered a package called ggpattern (https://github.com/coolbutuseless/ggpattern) that seems to be nice solution for this problem and integrates nicely with the ggplot2 workflow. While solutions using textures might work fine for diagonal bars, they will not produce vector graphics and are therefore not optimal.

    Here's an example taken straight from ggpattern's github repository:

    install.packages("remotes")
    remotes::install_github("coolbutuseless/ggpattern")
    
    library(ggplot2)
    library(ggpattern)
    
    df <- data.frame(level = c("a", "b", "c", 'd'), outcome = c(2.3, 1.9, 3.2, 1))
    
    ggplot(df) +
      geom_col_pattern(
        aes(level, outcome, pattern_fill = level), 
        pattern = 'stripe',
        fill    = 'white',
        colour  = 'black'
      ) +
      theme_bw(18) +
      theme(legend.position = 'none') + 
      labs(
        title    = "ggpattern::geom_pattern_col()",
        subtitle = "pattern = 'stripe'"
      ) +
      coord_fixed(ratio = 1/2)
    
    

    which results in this plot:

    If only some bars should be striped, geom_col_pattern() has a pattern_alpha argument that could be used to make certain unwanted stripes completely transparent.

提交回复
热议问题