相同的标题,完全重写了这个问题.
为什么alpha工作在第一个图而不是第二个?我很难理解为什么使用硬编码的值在正确的位置绘制rect而不是透明但是在data.frame中它按预期工作?
mtcars$cyl <- factor(mtcars$cyl)
mtcars$am <- factor(mtcars$am)
ggplot(mtcars) +
geom_density(aes(x=disp, group=cyl, fill=cyl), alpha=0.6, adjust=0.75) +
geom_rect(data=data.frame(xmin=100, xmax=200, ymin=0, ymax=Inf), aes(xmin=xmin, xmax=xmax, ymin=ymin,ymax=ymax), fill="red", alpha=0.2)
ggplot(mtcars) +
geom_density(aes(x=disp, group=cyl, fill=cyl), alpha=0.6, adjust=0.75) +
geom_rect(aes(xmin=100, xmax=200, ymin=0,ymax=Inf), fill="red", alpha=0.2)
Run Code Online (Sandbox Code Playgroud)
sc_*_*ans 100
谢谢你澄清了你的问题.这对我来说很困惑,所以我去谷歌,最后学习了一些新东西(在他们的例子中解决了一些变幻莫测的问题之后).显然你正在做的是在彼此之上绘制许多矩形,有效地消除了你想要的半透明度.因此,解决这个问题的唯一方法是在单独的df中硬编码矩形坐标,或者......
ggplot() +
geom_density(data=mtcars, aes(x=disp, group=cyl, fill=cyl), alpha=0.6, adjust=0.75) +
geom_rect(aes(xmin=100, xmax=200, ymin=0,ymax=Inf), alpha=0.2, fill="red")
Run Code Online (Sandbox Code Playgroud)
...只是不要将您的data.frame全局分配给绘图.相反,只在你想要的图层中使用它(在这个例子中geom_density
),并让其他图层无df!或者,更好的是,使用annotate
从默认df下修改你的图:
ggplot(mtcars) +
geom_density(aes(x=disp, group=cyl, fill=cyl), alpha=0.6, adjust=0.75) +
annotate("rect", xmin=100, xmax=200, ymin=0, ymax=Inf, alpha=0.2, fill="red")
Run Code Online (Sandbox Code Playgroud)
后一种方法使您可以为整个绘图使用单个data.frame,因此您不必为每个图层指定相同的df.
两种方法都返回相同的图:
geo*_*ory 16
另一种解决方法是为geom_rect提供单行数据对象,以确保只绘制一个矩形:
ggplot(mtcars) +
geom_density(aes(x=disp, group=cyl, fill=cyl), alpha=0.6, adjust=0.75) +
geom_rect(data=mtcars[1,], aes(xmin=100, xmax=200, ymin=0,ymax=Inf), fill="red", alpha=0.2)
Run Code Online (Sandbox Code Playgroud)