Big space in between two plot functions after knitting to PDF

Hello everyone,

I'm trying to plot a basemap downloaded by dismo package together with a shapefile. However after knitting the PDF file, there is a big space in between these two lines:

plot(base.map)
plot(reproj.boundary, add = TRUE, border = "red", col = "transparent")

Is this a bug in rmarkdown or I am doing something wrong?

Thank you!

My Rmd file:

---
title: "Mapping with R"
date: "February, 2018"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

# install.packages(c("hydroMap", "dataRetrieval", "rgdal", "dismo"), 
#                  dependencies = TRUE, 
#                  repos = "http://cran.us.r-project.org")

suppressMessages(library(hydroMap))
suppressMessages(library(dataRetrieval))
suppressMessages(library(rgdal))

sites <- "12488500"
siteInfo <- readNWISsite(sites)

# Download boundary
hydroMap::getBasin(sites, filePath = "./download")

boundary <- readOGR(dsn = "./download", layer = "epa_basins")
watershed_extent <- c(boundary@bbox[1], boundary@bbox[3],
                      boundary@bbox[2], boundary@bbox[4])

# Pass object to plot as first argument and map-type as second
base.map <- dismo::gmap(boundary, type = "terrain")

# Reproject watershed boundary to be the same as Google Map base.map
reproj.boundary <- spTransform(boundary, base.map@crs)

# Plot
plot(base.map)
plot(reproj.boundary, add = TRUE, border = "red", col = "transparent")

It looks like your base map isn't plotting at all (from what I can see). When an RMarkdown chunk is evaluated, the outputs will be printed as they are called (i.e. that base map is what's trying to go in that giant space), unless told otherwise. Since you call plot() twice, there are two plots being made. If you want to put the other elements over the base map (which I believe you do), you can either roll it into one call to plot, or stash that base map as an object and plot over it (I'm not all that familiar with the methods you're using, but in ggplot2 that would be roughly equivalent to assigning that first plot to p and then doing p + plot(...) (where ... is all the stuff in that second line)).

There are also knitr chunk options, such as fig.show = hold, that would let you delay printing until the end of the chunk.

3 Likes

Thank you @mara! The basemap was actually plotted in the figure at the end of the document (the terrain with a red boundary on top). I used option add = TRUE so the two could be plotted together.

When I included option fig.show='hold' as you suggested, it created a whole new blank page in between the codes and the actual figure

I might take a look at ggplot and ggmap later to see if those would fix the problem