Controlling plot order for visual objects with multiple geometries in ggplot2

I want ggplot to appear in a specific order to control what is visible when objects overlap. Each row of data is mapped to a composite of two layers of geometry - this requires plot specificity. I used a loop to do this, but it is very slow. I wonder if there is a better way? eg.

d = data.frame(x=c(1,5,2,2,4,2), y=c(1,1,4,3,3,5), grp=c(1,1,1,2,2,2)) ggplot(d, aes(x, y, group=grp)) + geom_polygon(aes(fill = factor(grp))) + geom_line(size=1) 

enter image description here

Each polygon line must be built with its polygon - for example, a red polygonal line must be closed by a blue polygon. Is there a way to achieve this without a loop when both geom_polygon and geom_line use the same dataset?


Edit: looping methods.

Here are the loop methods that I used. Added a better dataset for comparing performance. Both devices take about 5.6 seconds to work on my machine. For comparison, the typical approach ( ggplot(d, aes(x, y, fill=factor(grp))) + geom_polygon() + geom_line(size=1) ) takes 0.45 s.

 d = data.frame(x = sample(-30:30,99,rep=T) + rep(sample(1:100,33),each=3), y = sample(-30:30,99,rep=T) + rep(sample(1:100,33),each=3), grp = rep(1:33,each=3)) # Method 1 - for loop p = ggplot() for(g in unique(d$grp)){ dat = subset(d, grp == g) p = p + geom_polygon(data=dat, aes(x, y, fill = factor(grp))) + geom_line(data=dat, aes(x, y), size=1) } print(p) # Method 2 - apply ggplot() + lapply(unique(d$grp), FUN=function(g){ dat = subset(d, grp == g) list(geom_polygon(data=dat, aes(x, y, fill = factor(grp))), geom_line(data=dat, aes(x, y), size=1)) }) 

enter image description here

+5
source share
1 answer

I just used your code and ggplot2 layers in ggplot2 It looks like this

 d = data.frame(x=c(1,5,2,2,4,2), y=c(1,1,4,3,3,5), grp=c(1,1,1,2,2,2)) ggplot(d, aes(x, y, group=grp)) + geom_line(size=1)+ geom_polygon(aes(fill = factor(grp))) 

And the result is this

enter image description here

Also note that if you delete the geom_line call, you get the same result, but without a frame.

+1
source

Source: https://habr.com/ru/post/1237072/


All Articles