如何使用 ggplot2 透明地遮蔽水平线下的区域?

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

这是原图。

这是我用来生成上图的代码。

## 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 ")

我想在图中的水平线下方填充颜色。我已经尝试 geom_rect 通过修改上面代码的最后一行如下。

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")

得到如下图

我不需要深蓝色。我需要透明度,以便也可以查看平均条(黄色)。我也尝试过不同的 alpha 级别。但没有任何效果。感谢您的帮助。

解决方法: 我按照 LukeA 的建议修改了代码的最后一行。代码是

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)

并获得了如下所述的所需输出图。

谢谢大家

尝试这样的事情

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