使用alpha和geom_polygon时防止混合

时间:2017-06-27 21:06:40

标签: r plot ggplot2 transparency polygon

我使用geom_polygon覆盖数据,但由于它们合并在一起,因此无法区分颜色。这使得更多层次更糟糕。

如何确保颜色不混合?

示例数据

newdat <- structure(list(x = c(0, 0.77, 1.54, 2.31, 3.08, 3.85, 4.62, 5.38, 
6.15, 6.92, 7.69, 8.46, 9.23, 10, 10.77, 11.54, 12.31, 13.08, 
13.85, 14.62, 15.38, 16.15, 16.92, 17.69, 18.46, 19.23, 20, 20.77, 
21.54, 22.31, 23.08, 23.85, 24.62, 25.38, 26.15, 26.92, 27.69, 
28.46, 29.23, 30, 0, 0.77, 1.54, 2.31, 3.08, 3.85, 4.62, 5.38, 
6.15, 6.92, 7.69, 8.46, 9.23, 10, 10.77, 11.54, 12.31, 13.08, 
13.85, 14.62, 15.38, 16.15, 16.92, 17.69, 18.46, 19.23, 20, 20.77, 
21.54, 22.31, 23.08, 23.85, 24.62, 25.38, 26.15, 26.92, 27.69, 
28.46, 29.23, 30), y = c(0, 0, 0, 0, 0, 0, 0.01, 0.01, 0.02, 
0.03, 0.04, 0.05, 0.06, 0.06, 0.06, 0.06, 0.06, 0.06, 0.05, 0.04, 
0.03, 0.03, 0.02, 0.02, 0.02, 0.01, 0.01, 0.01, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0.01, 0.02, 0.03, 0.05, 
0.06, 0.08, 0.09, 0.1, 0.1, 0.1, 0.1, 0.09, 0.08, 0.07, 0.06, 
0.05, 0.05, 0.05, 0.04, 0.03, 0.02, 0.01, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0), type = c("a", "a", "a", "a", "a", "a", "a", "a", 
"a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", 
"a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", 
"a", "a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "b", "b", 
"b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", 
"b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", 
"b", "b", "b", "b", "b", "b", "b")), .Names = c("x", "y", "type"
), row.names = c(NA, -80L), class = "data.frame")

代码

library(ggplot2)

# Using polygon blends colors    
ggplot(newdat, aes(x = x, y = y, fill = type)) + geom_polygon(alpha = 0.1)

# But using line shows they are different
ggplot(newdat, aes(x = x, y = y, color = type)) + geom_line()

图解

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:3)

参数alpha设置透明度,这就是为什么你看到它们几乎相同;但是,解决方案并未将其设置为1,因为它导致看不到类型a

您可以将颜色设置为可以区分的颜色,同时增加alpha

   ggplot(newdat, aes(x = x, y = y, fill = type )) + geom_polygon(alpha = 0.3) +
          scale_fill_manual(values = c('red','lightblue')) 

哪个情节:

 


             https://i.stack.imgur.com/3v7XI.png