Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Combining ggplot and regular [native] R graphics in the same figure


Last week when trying to generate some awsome summary graphic, I came across the painful ordeal of trying to combine ggplot elements with a number of regular R graphic elements.

First things first, I had used grid.arrange module from gridExtra package to juxtapose ggplot elements in a panel figure. Furthermore, I had combined regular R [read non-ggplot] figures thru the good old par functionality.

Brief summary:

We will be making calls to viewport module from the gridBase package to generate---guess what---view ports into which ggplot objects are plotted. Interestingly, ggplot elements need not be a single simple ggplot object, but could be an arrangement of multiple objects bundled together using arrangeGrob module from gridExtra.

But before (and I emphasize before!) all that, we have to plot all regular R graphic elements in their respective layouts using par. Keep in mind that we have to save space for the ggplot elements to be added; this is possible by making calls to

Example Snippet:


# say I would like to have my regular R graphic in top-right quadrant
par(mfrow = c(2,2), mar=c(0,0,0,0), oma=c(0,0,0,0))

# leave top-left quadrant empty!

# plot regular R graphic in top-right quadrant
plot(seq(1:10), seq(1:10), pch = 20)

# now add the first ggplot element which is going to take
# up the left two quadrants
vp <- viewport(height = unit(1,"npc"), width=unit(0.5, "npc"), 
              just = c("left","top),
              y = 1, x = 0.5)
print(my.first.ggplot.obj, vp = vp)

# add the second ggplot element in the bottom right quadrant
vp <- viewport(height = unit(1,"npc"), width=unit(0.5, "npc"), 
              just = c("left","top),
              y = 0.5, x = 0.5)
print(my.second.ggplot.obj, vp = vp)


Voila! Here is the awesome-looking panel figure!



This comment has been minimized.

Copy link

commented Apr 30, 2018

Thanks, Just want to let you know that you missed a " after top in the viewport function : just = c("left","top),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.