【问题标题】:Adding patterns or textures to geom_bar() / geom_col() bars?向 geom_bar() / geom_col() 条添加图案或纹理?
【发布时间】:2018-01-28 14:38:00
【问题描述】:

有时,我需要为 geom_bar() / geom_col() 条设置某种图案或纹理(即,用于黑白打印)。例如,某些人可能难以查看以下内容:

library(ggplot2)
library(dplyr, warn.conflicts=FALSE)
library(tidyr)

d <- iris %>% 
    group_by(Species) %>% 
    summarize_all(mean) %>% 
    gather(key, val, -Species)

ggplot(d, aes(x = Species, y = val, fill = key)) +
    geom_col(position = "dodge") +
    scale_fill_grey()

good questions and answers on Stack Overflow(也有here)。然而,解决方案很复杂,基本上涉及手工创建图案或纹理。我想知道是否有人有一般的想法或建议或以不同方式解决此问题的新方法。很多时候,当我认为我不能用 ggplot2 做某事时,这意味着改变我对解决它的看法——但其他(罕见的)时候它还没有实现!

【问题讨论】:

标签: r ggplot2


【解决方案1】:

您可以使用ggpattern package添加模式

# remotes::install_github("coolbutuseless/ggpattern")
library(ggpattern)
library(ggplot2)
library(dplyr, warn.conflicts=FALSE)
library(tidyr)
  
  d <- iris %>% 
    group_by(Species) %>% 
    summarize_all(mean) %>% 
    gather(key, val, -Species)
  
  ggplot(d, aes(x = Species, y = val, fill = key)) +
    geom_col_pattern(position = "dodge",
             pattern = 
               c(
                 "stripe", "stripe", "stripe", # 3rd col
                 "stripe", "stripe", "stripe", # 4th col
                 "none", "none", "none", # 1st col
                 "crosshatch", "crosshatch", "crosshatch" # 2nd col
             ),
             pattern_angle = c(rep(0, 3), 
                               rep(45, 3), 
                               rep(0, 6)),
             pattern_density = .1,
             pattern_spacing = .04,
             pattern_fill = 'black') +
    scale_fill_grey() +
  guides(fill = guide_legend(override.aes = 
                               list(
                                 pattern = c("none", "crosshatch", "stripe", "stripe"),
                                 pattern_spacing = .01,
                                 pattern_angle = c(0, 0, 0, 45)
                                 )
                             ))

reprex package (v0.3.0) 于 2021-01-13 创建

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 2017-06-19
    • 2015-11-10
    • 1970-01-01
    相关资源
    最近更新 更多