ggplot:根据列值进行去饱和/制作灰色条

时间:2018-12-21 06:30:15

标签: r ggplot2

我想使条形图中的某些条饱和度降低(或变成灰色)。我根据如何使用alpha=column_name中的geom_bar基于列值,使某些条形比其他条形更加透明。但是我想使它们变灰而不透明。有没有办法在ggplot中本地执行此操作?

下面是使某些列基于S列透明的代码。是否有一种方法可以基于列的值对特定的灰色条进行去饱和/饱和处理?

已编辑代码以包含数据。

data_t<-as.data.frame(Titanic)

     join_table<- data_t %>% group_by(X=Class) %>% summarise(Y=sum(Freq)) %>% 
mutate(S=ifelse(Y-mean(Y)>0,"a","b")) %>% select(X,  S); join_table

     data_t %>% group_by(X=Class, groups=Sex) %>% summarise(Y=sum(Freq)) %>%
       inner_join(join_table, by=c("X"))  %>%
       ggplot(aes(x=X, y=Y)) + theme_minimal() +
       geom_bar(aes(fill=groups, alpha=S), stat = "identity", position = "dodge")         

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以子集每次绘制的数据,并相应地调整fill的颜色。以下应该起作用:

library(tidyverse)
data_t <- as.data.frame(Titanic)

join_table <- data_t %>% 
               group_by(X = Class) %>% 
               summarise(Y = sum(Freq)) %>% 
               mutate(S = ifelse(Y - mean(Y) > 0, "a", "b")) %>% 
               select(X, S)

data_t %>% 
  group_by(X = Class, groups = Sex) %>% 
  summarise(Y = sum(Freq)) %>%
  inner_join(join_table, by = c("X"))  %>%
  ggplot(aes(x = X, y = Y)) + 
    theme_minimal() +
    geom_bar(data = . %>% filter( S == "b"), 
             aes(fill = groups), stat = "identity", position = "dodge") +
    geom_bar(data = . %>% filter( S == "a"),
            aes(group = groups),
             fill = "grey80", stat = "identity", position = "dodge")

您可以调整fill = "grey80"以获得所需的确切颜色。