Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在ggplot上为矩形层设置alpha比例时出现意外行为_R_Ggplot2 - Fatal编程技术网

R 在ggplot上为矩形层设置alpha比例时出现意外行为

R 在ggplot上为矩形层设置alpha比例时出现意外行为,r,ggplot2,R,Ggplot2,总之,我不确定这个例子出了什么问题: 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')) 库(ggplot2) pa

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

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'))
库(ggplot2)
par(ask=TRUE)

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

我提出的解决方案包括:(1)将矩形数据放在它自己的data.frame中,(2)在每个层中分别指定数据(但不是在
ggplot()
调用中)


另一种方法是使用
annotate
而不是
geom\u rect

ggplot(dat, aes(x = x, y = y)) +
  geom_point()+
    annotate("rect", xmin = 20, xmax = 70, ymin = 0, 
             ymax = 100, fill = "black", alpha = 0.3) 
输出:

数据:


dat是的,这似乎是前进的方向。在浏览了其他几个在线示例后,我意识到它们都做了相同的事情,为着色矩形对象创建了一个单独的df。谢谢
# 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(dat, aes(x = x, y = y)) +
  geom_point()+
    annotate("rect", xmin = 20, xmax = 70, ymin = 0, 
             ymax = 100, fill = "black", alpha = 0.3) 
dat <- structure(list(x = 1:100, y = 1:100),
                 class = "data.frame",
                 row.names = c(NA, -100L))