下面是带有facet_wrap的ggplot条形图的简单代码:
categories <- c("category 1", "category 2", "category 3")
groups <- c("A", "B", "C", "D")
df <- expand.grid(category = categories, group = groups)
df$value <- rnorm(12, 1, 0.5)
ggplot(df, aes(x = category,
y = value)) +
geom_bar(stat = "identity") +
facet_wrap(~ group)
现在我希望 C 组的条形为红色(仅针对 C 组)。我该怎么办?
这与我链接的另一个问题非常相似。但是,您的评论表明其中的联系并不明确。关键是要意识到您正在通过
group
设置颜色,但是您可以设置颜色并通过同一列创建面。
定义你的颜色:
colors <- rep("grey50", length(unique(df$group))) |>
setNames(unique(df$group))
colors["C"] <- "red"
# `colors` is a named vector that looks like this:
# A B C D
# "grey50" "grey50" "red" "grey50"
fill
美学设置为group
的绘图,并使用scale_fill_manual()
来指定我们定义的colors
:
ggplot(df, aes(
x = category,
y = value
)) +
geom_bar(stat = "identity", aes(fill = group)) +
scale_fill_manual(values = colors) +
facet_wrap(~group)