仅更改一个方面面板中条形的颜色

问题描述 投票:0回答:1

下面是带有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 组)。我该怎么办?

r ggplot2 geom-bar facet-wrap
1个回答
0
投票

这与我链接的另一个问题非常相似。但是,您的评论表明其中的联系并不明确。关键是要意识到您正在通过

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)

© www.soinside.com 2019 - 2024. All rights reserved.