Change opacity on part of geom_bar

I am trying to change the opacity of a ggplot graph plot. Consider the following example:

df <- data.frame(period = rep(c("current", "past"), 3), 
                 type = c("so_far", "so_far", "source_x", "source_x", "source_y", "source_y"), 
                 income = c(12, 10, 7, 9, 4, 7))
ggplot(df, aes(x = period, y = income, fill = type)) + geom_bar(stat = "identity")

This gives the following graph: enter image description here

In fact, although source_x and source_y are estimates during the current period, they are true values ​​in the past. Therefore, I want to change the opacity of only the blue and green parts in the left sidebar. It can be done? How?

+4
source share
1 answer

, , . , -, . , .

library(ggplot2)

ggplot(df, aes(x = period, y = income, fill = type, 
               linetype=ifelse(grepl("current", period) & grepl("source", type), "B", "A"),
               alpha=ifelse(grepl("current", period) & grepl("source", type), 0, 1))) + 
  geom_bar(stat = "identity", lwd=0.5, colour="grey40") +
  scale_alpha(range=c(0.5,1)) + 
  theme_bw() +
  guides(alpha=FALSE, linetype=FALSE,
         fill=guide_legend(reverse=TRUE))

enter image description here

+6

Source: https://habr.com/ru/post/1659456/


All Articles