Search code examples
rplotggplot2transparencypolygon

Prevent blending when using alpha and geom_polygon


I'm overlaying data using geom_polygon, but the colors cannot be distinguished because they merge together. This makes it even worse with more layers.

How do you ensure the colors do not blend?

Sample data

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

Code

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

Plots

enter image description here

enter image description here


Solution

  • Parameter alpha set transparency so that's why you see them almost the same; however, the solution is not setting it to 1 as it causes to not see type a.

    You can set colors to those which can be distinguished and increasing alpha in the meantime:

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

    Which plots:

     
    
    
                 https://i.sstatic.net/3v7XI.png