pengchy
pengchy

Reputation: 820

highlight interested regions across multiple facets in ggplot2

I have googled thoroughly but only found this questions "Highlight data individually with facet_grid in R".

dt <- data.frame(
  a = rep(letters[1:4],each=250),
  dirct = rep(c("Up","Down"),500),
  term = rep(letters[1:25],400),
  logp = runif(1000)
  )

ggplot(dt,aes(term,logp,fill=dirct))+
  facet_grid(.~a) +
  geom_bar(position="dodge",width=0.8,stat="identity")+
  scale_fill_manual("dirct",values=c("red","blue"))+
  coord_flip()+
  theme(axis.text.y=element_text(colour=c(rep("black",10),rep("red",15))))+
  geom_rect(aes(xmin=rep(0.5,1000),xmax=rep(10.5,1000),
                ymin=-Inf,ymax=Inf),fill="green",alpha=30/200,inherit.aes=FALSE)+
  geom_rect(aes(xmin=rep(10.5,1000),xmax=rep(25.5,1000),
                ymin=-Inf,ymax=Inf),fill="gray",alpha=30/200,inherit.aes=FALSE)+
  geom_vline(aes(xintercept=1:25),color="white") +
  geom_hline(aes(yintercept=seq(0,1,0.25)),color="white") +
  geom_bar(position="dodge",width=0.8,stat="identity")

Here I have implemented the how to highlight regions across multiple facets. My question is:

Is it possible to add the interested region as the background. So it will no need to redraw the geom_bar

Thank you for your reply!

Upvotes: 0

Views: 723

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70653

I couldn't solve the replotting of barplot, but I did manage to solve the transparency issue.

green.data <- data.frame(xmin = 0.5, xmax = 10.5, ymin = -Inf, ymax = Inf, a = c("a", "b", "c", "d"))
# grey.data <- data.frame(xmin = 10.5, xmax = 25.5, ymin = -Inf, ymax = Inf, a = c("a", "b", "c", "d"))
ggplot() +
  geom_bar(data = dt, aes(x = term, y = logp, fill = dirct), position = "dodge", width = 0.8, stat = "identity") +
  geom_rect(data = green.data, aes(xmin = xmin, ymin = ymin, xmax = xmax, ymax = ymax), fill = "green", alpha = 15/100) +
#   geom_rect(data = grey.data, aes(xmin = xmin, ymin = ymin, xmax = xmax, ymax = ymax), fill = "grey", alpha = 0.2) +
  geom_bar(data = dt, aes(x = term, y = logp, fill = dirct), position = "dodge", width = 0.8, stat = "identity") +
  scale_fill_manual("dirct", values = c("red", "blue")) +
  coord_flip() +
  facet_grid(. ~ a)

enter image description here

Upvotes: 1

Related Questions