在ggplot2/facet_grid中,如何更改列
a
和b
在facetgap
中填充红色?
library(tidyverse)
data <- data.frame(category=c('a','b','c','d'),actual=c(10,7,6,3),budget =c(11,12,4,1))
data %>% mutate(gap = actual - budget) %>% gather(key='item',value='amount',-category) %>%
ggplot(aes(x=category,y=amount,fill=item))+
geom_col()+
scale_fill_brewer(palette = "Spectral",direction=1)+
facet_wrap(~ item,ncol=1)
我尝试将
geom_col()
替换为 geom_col(aes(fill = if_else(amount<0 & item=='gap','red','lightblue')))
,但失败了
data %>% mutate(gap = actual - budget) %>% gather(key='item',value='amount',-category) %>%
ggplot(aes(x=category,y=amount,fill=item))+
geom_col(aes(fill = if_else(amount<0 & item=='gap','red','lightblue')))+
scale_fill_brewer(palette = "Spectral",direction=1)+
facet_wrap(~ item,ncol=1)
一种方法是使用嵌套的
ifelse
和 scale_fill_manual
:
data %>%
mutate(gap = actual - budget) %>%
gather(key = 'item', value = 'amount', -category) %>%
ggplot(aes(x = category, y = amount, fill = item)) +
geom_col(aes(fill = ifelse(amount < 0 & item == 'gap', 'gap2',
ifelse(amount > 0 & item == 'gap', 'gap1', item)))) +
scale_fill_manual(values = c(brewer_pal(palette = "Spectral", direction = 1)(3), 'red')) +
facet_wrap(~ item, ncol = 1)