使用 ggplot2 的堆叠条形图上的透明层

transparent layers on a stacked bar plot using ggplot2

dt1 <- data.frame(yr=c(2010,2010,2011,2011), val=c(1500,3000,2000,1100), x=c("a","b","a","b"))
dt1$alphayr <- as.factor(ifelse(dt1$yr == "2011", 0.5, 1))

ggplot() + geom_bar(data=dt1, aes(x=yr, y=val, fill=x, alpha=factor(alphayr)), stat="identity") +
  scale_x_continuous(breaks=dt1$yr) +
  scale_alpha_manual(values = c("0.5"=0.2, "1"=1), guide='none')

我需要控制哪些层是透明的,而不是控制哪些整个条是透明的。

如何使所有最底层都 100% 透明?

看起来你可以通过在 x == "b":

的任何地方设置 alpha = 0 来实现你想做的事情
library(ggplot2)
library(dplyr)

dt1 <- tibble(yr=c(2010,2010,2011,2011), val=c(1500,3000,2000,1100), x=c("a","b","a","b")) %>% 
  mutate(alphayr = ifelse(x == "b", 0, 1))

ggplot(dt1) + 
  geom_col(aes(x = yr, y = val, fill = x, alpha = alphayr)) +
  scale_alpha_identity()