Themagrittr package provides several different types ofpipes which can be a handy way to organize computation, especially whenthe computation involves processing data for input to another procedure,in this caseggplot():
library(dplyr)# load this to also have dplyr functionalitylibrary(magrittr)library(ggplot2)p1_piped<- mtcars%>%rename(transmission = am,weight = wt)%>%mutate(lp100km = (100*3.785411784)/ (1.609344* mpg))%>%select(weight, lp100km)%>%ggplot(aes(x = weight,y = lp100km))+geom_point()+ylab("Litres per 100 kilometres")+ggtitle("Gas usage")Here the “pipe”%>% takes the output of its left handside and pushes it into the first argument of its right hand side.Arbitrary many pipes may be gathered together.
This connects nicely withggplot2’s addition+operator (+ itself is sometimes a pipe, sometimes a layeringgplot construction) to create theggplotfrom the data and assign it top1_piped.
Two things to note here are. First, the result of the datamanipulation is assigned at the beginning using the<-assignment function which seems to run counter to the data flowindicated by the pipes. A more consistent flow would be to have insteadwritten
mtcars%>%rename(transmission = am,weight = wt)%>%mutate(lp100km = (100*3.785411784)/ (1.609344* mpg))%>%select(weight, lp100km)%>%ggplot(aes(x = weight,y = lp100km))+geom_point()+ylab("Litres per 100 kilometres")+ggtitle("Gas usage")-># Note assignment occurs here p1_pipedNow the assignment operator-> is used at the end,matching the data flow of the pipes.
Second, in either case theggplot isnot itself displayed (or rendered) until it isprinted.
Once built, as happens when the plot has been displayed as above, aninteractive loon plot can be had as always, simply by callingggplot2loon() on the builtggplot:
Again, the additional specification here of thelinkingGroup will cause display attributes to be pulledfrom the plots in that linking group.
gg_pipe(data, ggplotObj)Note that before aggplot can be displayed, a number ofsteps are performed so as to prepare the plot object for rendering(e.g. seeggplot2::ggplot_build). Unfortunately, this delayin completing the preparation of theggplot can make itdifficult to attach further operations in the%>%pipeline after theggplot itself – apart of course fromfurtherggplot2 additions via the+ operator.For example, one cannot simply add%>% ggplot2loon() atthe end of the pipeline used to construct theggplot. Thatis,
mtcars%>%rename(transmission = am,weight = wt)%>%mutate(lp100km = (100*3.785411784)/ (1.609344* mpg))%>%select(weight, lp100km)%>%ggplot(aes(x = weight,y = lp100km))+geom_point()+ylab("Litres per 100 kilometres")+ggtitle("Gas usage")%>%ggplot2loon()would produce neither aggplot or an interactiveloon plot.
To get around this problem, inloon.ggplot the functiongg_pipe() is provided to encapsulate theggplot construction in any pipeline and force theggplot to be built (though not rendered in a display). Theoutput of this function can then be passed on toggplot2loon().
For example,
mtcars%>%rename(transmission = am,weight = wt)%>%mutate(lp100km = (100*3.785411784)/ (1.609344* mpg))%>%select(weight, lp100km)%>%# encapsulate the ggplot construction with gg_pipe()gg_pipe(ggplot(aes(x = weight,y = lp100km))+geom_point()+ylab("Litres per 100 kilometres")+ggtitle("Gas usage") )%>%# and pass the built plot onggplot2loon(linkingGroup ="Motor Trend 1974")constructs the interactive plot which could have been assigned to avariable as was done with the originalggplotconstruction.
From here, the pipeline can be grown as before, recognizing of coursethat the output ofggplot2loon() is aloonplot of some sort. This means that functions that operate onloon plots (as their first argument can be used). As withany piping operation, attention must be given to the first argument ofthe functions in the pipeline as well as to what the input and outputsare of any function.
For example,
mtcars%>%rename(transmission = am,weight = wt)%>%mutate(lp100km = (100*3.785411784)/ (1.609344* mpg))%>%select(weight, lp100km)%>%# encapsulate the ggplot construction with gg_pipe()gg_pipe(ggplot(aes(x = weight,y = lp100km))+geom_point()+ylab("Litres per 100 kilometres")+ggtitle("Gas usage") )%>%# and pass the built plot onggplot2loon(linkingGroup ="Motor Trend 1974")%>%# pipe the loon plot onl_cget('color')# Gets and returns the vector of point coloursIn themagrittr package (the source of the pipelineoperation) there are a variety of pipeline operators which might also beuseful – not just%>%.
l_ggplot()Additionally, using functionl_ggplot, can also create aloon plot withggplot pipe model.
The display ofggplot object relies on the defaultprint() function inR. Functionl_ggplot, inserts a new classl_ggplot intothe originalggplot object. At the printing time,S3 methodprint.l_ggplot() will be executed to transform aggplot plot to aloon plot.
obj<- mtcars%>%rename(transmission = am,weight = wt)%>%mutate(lp100km = (100*3.785411784)/ (1.609344* mpg))%>%select(weight, lp100km)%>%# replace `ggplot` to `lggplot`l_ggplot(aes(x = weight,y = lp100km))+geom_point()+ylab("Litres per 100 kilometres")+ggtitle("Gas usage")objHowever, this design has an obvious drawback: confusion of the outputdata structure. Since the transformation is accomplished at the printingtime, objectobj is still aggplot datastructure. To create aloon “handle”, we have to usel_getFromPath()
if(utils::packageVersion("loon")>="1.2.4") {# **THIS IS IMPORTANT**# The path name can be obtained at the top left tk window# Suppose the label is "loon.ggplot --path: .l13.ggplot"# The path would be the char right after "path: " which is ".l13.ggplot" loonWidget<-l_getFromPath(".l13.ggplot")class(loonWidget)# [1] "l_plot" "loon"}Of course, for plots already existing inloon,ggplot() and hencegg_pipe() could be avoidedentirely:
mtcars%>%rename(transmission = am,weight = wt)%>%mutate(lp100km = (100*3.785411784)/ (1.609344* mpg))%>%select(weight, lp100km)%>%# and pass the built plot onl_plot(title ="Gas Usage",showGuides =TRUE,showScales =TRUE,ylabel ="Litres per 100 kilometres",linkingGroup ="Motor Trend 1974")%>%plot()# get a static version via grid