geom_rect 和 alpha - 这是否适用于硬编码值? [英] geom_rect and alpha - does this work with hard coded values?

查看:33
本文介绍了geom_rect 和 alpha - 这是否适用于硬编码值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相同的标题,但完全改写了问题.

Same title, completely reworded the question though.

为什么 alpha 在第一个图中起作用,而在第二个图中不起作用?我很难理解为什么使用硬编码值,矩形被绘制在正确的位置,但没有变得透明,但是在 data.frame 中它按预期工作?

Why does the alpha work in the first plot but not the second? I'm struggling to see why with hardcoded values the rect is drawn in the right place but not made transparent but when in a data.frame it works as expected?

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) 

推荐答案

这让我很困惑,所以我去谷歌,结果 学习新东西(在他们的例子中解决了一些变幻莫测的问题之后).

This was puzzling to me, so I went to google, and ended up learning something new (after working around some vagaries in their examples).

显然,您正在做的是在彼此之上绘制许多矩形,从而有效地消除了您想要的半透明效果.因此,克服这个问题的唯一方法是在单独的 df 中对矩形坐标进行硬编码,或者...

Apparently what you are doing is drawing many rectangles on top of each other, effectively nullifying the semi-transparency you want. So, the only ways to overcome this are to hard-code the rectangle coordinates in a separate df, or...

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

...只是不要将您的 data.frame 全局分配给绘图.相反,仅在您想要的层中使用它(在本例中为 geom_density),而让其他层无 df !或者,更好的是,使用 annotate 从默认 df 下修改您的绘图:

... just don't assign your data.frame globally to the plot. Instead, only use it in the layer(s) you want (in this example, geom_density), and leave the other layers df-free! Or, even better yet, Use annotate to modify your plot out from under the default 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") 

后一种方法使您可以对整个图使用单个 data.frame,因此您不必为每一层指定相同的 df.

The latter method enables you to use a single data.frame for the entire plot, so you don't have to specify the same df for each layer.

两种方法都返回相同的图:

Both methods return identical plots:

这篇关于geom_rect 和 alpha - 这是否适用于硬编码值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆