有时,我需要为 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()
Run Code Online (Sandbox Code Playgroud)
Stack Overflow 上有很好的问题和答案(也在这里)。然而,解决方案很复杂,基本上涉及手工创建图案或纹理。我想知道是否有人有一般的想法或建议或以不同方式解决这个问题的新方法。通常,当我认为我不能用 ggplot2 做某事时,这意味着改变我对解决它的看法 - 但其他(罕见)时间它只是还没有实现!
# 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)
)
))
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2021 年 1 月 13 日创建(v0.3.0)