[R-sig-Geo] merge ggplots into one with pipeline commands

Kent Johnson kent3737 @end|ng |rom gm@||@com
Thu Feb 4 20:43:38 CET 2021


On Thu, Feb 4, 2021 at 6:01 AM <r-sig-geo-request using r-project.org> wrote

> Message: 3
> Date: Wed, 3 Feb 2021 16:10:17 +0000
> From: Marta Rufino <marta.m.rufino using gmail.com>
> To: r-sig-geo <r-sig-geo using r-project.org>
> Subject: [R-sig-Geo] merge ggplots into one with pipeline commands
> Message-ID:
>         <
> CAKSASLDyVVWgDJ6VT1ZWUEBoh8KbXufa+bv1UePi0YUABOz9CQ using mail.gmail.com>
> Content-Type: text/plain; charset="utf-8"
>
> Hi,
>
> I want to make one only ggplot by merging/joining a base ggplot and a
> ggplot resulting from a pipeline command (ddplyr).
>
> Here it is the reproducible example:
>
> # my base plot, for example:
> # https://rpubs.com/MRufino/Portugal
> p1 <- ggplot() +
>     borders("world",
>             fill="antiquewhite1",
>             colour="antiquewhite4")+
>   coord_fixed(ylim=c(36.6, 42.0), xlim=c(-10 ,-7))+
>   theme_minimal()+
>   theme(panel.background = element_rect(fill = 'powderblue'),
>         panel.grid.major = element_blank(),
>         panel.grid.minor = element_blank())+
>   xlab("Longitude")+ ylab("Latitude")
>  p1
>
> # now, if I want to add this plot to another ggplot resulting from a
> pipeline command, how can I do it?
> dat <- data.frame(lat=c(40.3,38.4,39),
>            lon = c(-10,-8,-9),
>            fac = c(1,2,1))
>
> # pipeline ggplot
> dat %>%
>   filter(fac==1) %>%
>   ggplot()+
>   geom_point(aes(x=lon, y=lat))
>

This will do it. Enclosing the pipe expression in { } lets you put the
piped-in variable where you need it using '.'.

dat %>%
  filter(fac==1) %>%
  { p1 +
    geom_point(data=., aes(x=lon, y=lat))
  }

Kent Johnson
Cambridge, MA

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list