Search code examples
rggplot2horizontal-line

How to shade a region under a horizontal line transparently using ggplot2?


This is the original image.

Original Image

This is the code i used to produce the above image.

## Employees Wise Sales Report: MAY 2014-LYNDA Best Visualization Assignment
setwd('d:/dataset/lynda')
empwisedata=read.csv('income.csv',header=T,sep=",")
names(empwisedata)
attach(empwisedata)

Minimum=c(min(Person1),min(Person2),min(Person3),min(Person4),min(Person5))
Average=c(mean(Person1),mean(Person2),mean(Person3),mean(Person4),mean(Person5))
Maximum=c(max(Person1),max(Person2),max(Person3),max(Person4),max(Person5))
attach(Average)

library(ggplot2)
library(reshape2)
df = melt(data.frame(Minimum,Average,Maximum,Employees=c("Person1", "Person2","Person3","Person4","Person5")),variable.name="IncomeLevels")
df$Employees<-factor(df$Employees,levels = df$Employees[order(Average)])

p=ggplot(df, aes(Employees, value, fill=IncomeLevels)) +   geom_bar(position="dodge",stat="identity")

p + geom_hline(yintercept=mean(Average))+scale_fill_manual(values=c("red","orange","dark green"))+labs(size= "Nitrogen", x = "Employees of ACME Widgets",y = "Income in USD", title = "ACME WIDGETS :: Employees Wise Sales Report-MAY 2014 ")

I would like to fill the color under the horizontal line in the graph. i had tried geom_rect by modifying the last line of above code as follows.

p+geom_hline(yintercept=mean(Average)) + scale_fill_manual(values=c("red","orange","dark green"))+labs(size= "Nitrogen", x = "Employees of ACME Widgets",y = "Income in USD", title = "ACME WIDGETS :: Employees Wise Sales Report-MAY 2014 ") + geom_rect(xmin=0,xmax=200,ymin=0,ymax=mean(Average),fill="blue")

and got the following image.

enter image description here

I dont need dark blue. I need transparency so that average bars (Yellow coloured) also viewed. I had tried with different alpha levels too. But nothing works. Your help is appreciated.

Solution: i had modified the last line of the code as per the advice of LukeA. The code is

p+geom_hline(yintercept=mean(Average))+scale_fill_manual(values=c("red","orange","dark green"))+labs(size= "Nitrogen", x = "Employees of ACME Widgets",y = "Income in USD", title = "ACME WIDGETS :: Employees Wise Sales Report-MAY 2014 ")+  annotate("rect", xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = mean(Average), fill = "blue", alpha = .1, color = NA)

and got the desired output plot as mentioned below. enter image description here

Thank you all.


Solution

  • Try something like this

    library(ggplot2)
    ggplot(mtcars, aes(mpg)) + 
      geom_histogram() + 
      annotate("rect", xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = 1, fill = "blue", alpha = .5, color = NA)
    

    enter image description here