gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:57:32 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com