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