Story points in front of lines for each group / ggplot 2 equivalent of type = "o"

Suppose I want to build a graph with points and lines, where points appear in front of their respective lines in each group. In particular, I want group 1 to be built with red filled dots where the points are connected by a line, but group 2 should be built with a (just) blue line, but I want group 2 to be built over group 1. For example, in base chart:

set.seed(101)
dd <- data.frame(x=rep(1:10,2),
         y=rep(1:10,2),
                 f=factor(rep(1:2,each=10)))
dd$y[11:20] <-     dd$y[11:20] + rnorm(10)
d1 <- subset(dd,f=="1")
d2 <- subset(dd,f=="2")

par(cex=1.5)
plot(y~x,data=d1,bg="red",pch=21,type="o")
lines(y~x,data=d2,col="blue",lwd=2)
legend("bottomright",c("group 1","group 2"),
       col=c("black","blue"),
       pch=c(21,NA),
       pt.bg=c("red",NA),
       lty=1,
       lwd=c(1,2))

enter image description here

(My real data is a little more complicated.) I'm going to make some nuts trying to do this in ggplot2.

If I draw dots in front of the lines, the points of the 1st group are superimposed with lines in the same group:

 library(ggplot2); theme_set(theme_bw())
 g0 <- ggplot(dd,aes(x,y,fill=f,colour=f,shape=f))+
     scale_fill_manual(values=c("red",NA))+
     scale_colour_manual(values=c("black","blue")) +
     scale_shape_manual(values=c(21,NA))
 g0 + geom_point()+  geom_line()
 ggsave("order2.png",width=3,height=3)

enter image description here

If I draw lines in front of the points, the lines of group 2 are superimposed with the points of group 1:

 g0 + geom_line()+  geom_point()
 ggsave("order3.png",width=3,height=3)

enter image description here

( 1- ), ( 1- ), ( 2). , , , .

 g0 +  geom_line() + geom_point()+ 
     geom_point(data=d1)+
     geom_line(data=d2,show.legend=FALSE)
 ggsave("order4.png",width=3,height=3)

, "" geom_linepoint, ; ... - ?

enter image description here

+4
1

"low tech" 1. , , .

linepoint = function(data, group.var, lsize=1.2, psize=4) {
  lapply(split(data, data[,group.var]), function(dg) {
    list(geom_line(data=dg, size=lsize),
         geom_point(data=dg, size=psize)) 
  })
}

ggplot(dd, aes(x,y, fill=f, colour=f,shape=f))+
  scale_fill_manual(values=c("red",NA))+
  scale_colour_manual(values=c("black","blue")) +
  scale_shape_manual(values=c(21,NA)) +
  linepoint(dd, "f")

enter image description here


1 " " . @baptiste ( ) , , , , .

+1

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


All Articles