为ggplot上的矩形图层设置alpha比例时出现意外的行为 [英] Unexpected behavior when setting alpha scale for rectangle layer on ggplot

查看:98
本文介绍了为ggplot上的矩形图层设置alpha比例时出现意外的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有,我不确定这个例子出了什么问题:

All, I'm not sure what's gone wrong with this example:

library(ggplot2)
par(ask = TRUE) 
alphaVals <- seq(0.1, 1, 0.1)
for(alpha in alphaVals) print(qplot(x = 1:100, y = 1:100) + geom_rect(xmin = 20, xmax = 70, ymin = -Inf, ymax = Inf, alpha = alpha, fill = 'grey50'))

您可以看到,从alpha等于0到大约0.2,我获得了一些透明度,但在此之后它就消失了。我从来没有遇到过设置ggplot2图层的alpha比例的问题。

You can see that from alpha equals 0 to around 0.2 I get some transparency, but after that it's just gone. I've never had problems setting the alpha scale of a ggplot2 layer before.

我在这里做错了什么?

What am I doing wrong here?

干杯,
Aaron

Cheers, Aaron

推荐答案

ggplot2是在相同的位置绘制矩形100次。因此,100个堆叠的透明形状呈现为单个不透明形状。通过使用Adobe Illustrator检查pdf输出,我发现了这一点。我在下面提供了一个可能的解决方案(重写为使用ggplot语法而不是qplot)。我确实认为这种行为是出乎意料的,但我不确定它是否值得被称为bug。

The problem here is that ggplot2 is drawing the rectangle 100 times in the same location. Thus, 100 stacked transparent shapes appear as a single opaque shape. I discovered this by inspecting the pdf output with Adobe Illustrator. I have provided a possible solution below (re-written to use ggplot syntax instead of qplot). I certainly feel that this behavior is unexpected, but I'm not sure if it deserves to be called a bug.

我提出的解决方案包括(1)将矩形数据在它自己的data.frame中,并且(2)在每一层单独指定数据(但不在 ggplot()调用中)。

My proposed solution involves (1) putting the rectangle data in its own data.frame, and (2) specifying the data separately in each layer (but not in the ggplot() call).

library(ggplot2)

dat  = data.frame(x=1:100, y=1:100)
rect_dat = data.frame(xmin=20, xmax=70, ymin=0, ymax=100)

# Work-around solution.
p = ggplot() + 
    geom_point(data=dat, aes(x=x, y=y)) + 
    geom_rect(data=rect_dat, 
              aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax),
              alpha = 0.3, fill = "black")

ggsave("test.png", plot=p, height=5, width=5, dpi=150)


# Original version with 100 overlapping rectangles.
p2 = ggplot(dat, aes(x=x, y=y)) + 
     geom_point() + 
     geom_rect(xmin=20, xmax=70, ymin=0, ymax=100, alpha=0.01, fill="black")

ggsave("test.pdf", height=7, width=7)

这篇关于为ggplot上的矩形图层设置alpha比例时出现意外的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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