问题描述
有时,我需要geom_bar()/geom_col()条(例如,用于黑白打印)的某种图案或纹理.例如,某些人可能难以理解以下内容:
库(ggplot2)库(dplyr,warn.conflicts = FALSE)图书馆(tidyr)d<-虹膜%&%;%group_by(物种)%>%summary_all(mean)%&%;%收集(键,值,-种类)ggplot(d,aes(x =种,y = val,填充=键))+geom_col(position ="dodge")+scale_fill_grey()
在Stack Overflow上有(v0.3.0)创建于2021年1月13日
On occasion, I have the need for some kind of pattern or textures for geom_bar() / geom_col() bars (i.e., for black-and-white printing). For example, the following can be hard for some people to view:
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()
There have been good questions and answers on Stack Overflow (also here). However, the solutions are complicated and basically involve creating the patterns or textures by hand. I'm wondering if anyone has general ideas or suggestions or new approaches to solving this problem in a different way. Oftentimes when I think I can't do something with ggplot2, it means changing how I think about addressing it - but other (rare) times it just isn't implemented yet!
You can add patterns using the 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)
)
))
这篇关于在geom_bar()/geom_col()条中添加图案或纹理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!