在ggplot2/facet_wrap中,在给定的facet中,如何更改特定列的填充颜色

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

在ggplot2/facet_grid中,如何更改列

a
b
在facet
gap
中填充红色?

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)
ggplot2 facet-wrap
1个回答
0
投票

一种方法是使用嵌套的

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)

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