r - 向 geom_bar()/geom_col() 条添加图案或纹理?

标签 r ggplot2

有时,我需要为 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()

example bar chart

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

最佳答案

您可以使用 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)
                                 )
                             ))

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

关于r - 向 geom_bar()/geom_col() 条添加图案或纹理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48487498/

相关文章:

r - R 中的 ggplot2 : geom_segment displays different line than geom_line

r - 使用长格式的数据计算基线的变化

r - 在此示例中,在 tidyverse 和 ggplot 中订购箱线图的最简单方法是什么?

R:将数据框减少为跨两列完全匹配的行

r - ggplot2 - 条形图与误差线不对齐

r - 如何使用 ggplot2 从 qcc 包重现 pareto.chart 图?

regex - R字符串在拆分时删除标点符号

mysql - RMySQL 系统错误 : 10060

r - ggplot2 中的语音注视事件图

r - ggplot geom_point : how to set font of custom plotting symbols?