基于ggplot2包,我想向条形图的不同条形添加不同的纹理。此外,我想将这些纹理添加到小节的图例中。
考虑以下可重复的示例:
# Create example data
data_ggp <- data.frame(category = rep(c("cat1", "cat2", "cat3"), 4),
values = c(0.664, 0.045, 0.291, 0.482, 0.029, 0.489, 0.537, 0.027, 0.436, 0.536, 0.028, 0.436),
group = c(rep("group1a", 3), rep("group1b", 3), rep("group2a", 3), rep("group2b", 3)))
# Load ggplot2
library("ggplot2")
# Draw barchart (not overlayed)
ggplot(data_ggp, aes(category, values)) +
geom_bar(stat = "identity", aes(fill = group), position = "dodge") +
scale_fill_manual(" ",
labels = c("group1a", "group1b", "group2a", "group2b"),
values = c("group1a" = "deepskyblue4", "group1b" = "darkolivegreen4",
"group2a" = "deepskyblue1", "group2b" = "darkolivegreen2"))
对于此条形图,我想对第2a组绘制对角线,对第2b组绘制垂直+水平线。图例也应包含这些纹理。
最终的barplot应该如下所示(用油漆绘制):
我在堆栈溢出中发现了一个相对较旧的线程:How to add texture to fill colors in ggplot2?
不幸的是,此代码非常复杂,无法自动执行,并且难以应用于不同类型的条形图。此外,我想将纹理添加到我的图例中。
问题:如何将不同的纹理添加到条形图的不同条上+添加到条形图例中?
答案 0 :(得分:1)
我可以使用 ggpattern
解决这个问题# remotes::install_github("coolbutuseless/ggpattern")
library(ggpattern)
library(ggplot2)
data_ggp <- data.frame(category = rep(c("cat1", "cat2", "cat3"), 4),
values = c(0.664, 0.045, 0.291, 0.482, 0.029, 0.489, 0.537, 0.027, 0.436, 0.536, 0.028, 0.436),
group = c(rep("group1a", 3), rep("group1b", 3), rep("group2a", 3), rep("group2b", 3)))
ggplot(data_ggp, aes(category, values)) +
geom_bar_pattern(stat = "identity",
pattern = c("none", "none", "none", # 1st col
"none", "none", "none", # 2nd col
"stripe", "stripe", "stripe", # 3rd col
"crosshatch", "crosshatch", "crosshatch" # 4th col
),
pattern_angle = c(rep(0, 6), rep(45, 3), rep(0, 3)),
pattern_density = .1,
pattern_spacing = .04,
pattern_fill = 'black',
aes(fill = group),
position = "dodge") +
scale_fill_manual(" ",
labels = c("group1a", "group1b", "group2a", "group2b"),
values = c("group1a" = "deepskyblue4", "group1b" = "darkolivegreen4",
"group2a" = "deepskyblue1", "group2b" = "darkolivegreen2")) +
guides(fill = guide_legend(override.aes =
list(
pattern = c("none", "none", "stripe", "crosshatch"),
pattern_spacing = .01,
pattern_angle = c(0, 0, 45, 0)
)
))
由 reprex package (v0.3.0) 于 2021 年 1 月 13 日创建