MCP_infiltrator
MCP_infiltrator

Reputation: 4179

Embed ggplot2 Graph in Knitr Document: Unable to find function ggplot

I am working on a document and am using both knitr and ggplot2. I am new to knitr and TeX itself and therefore not overly familiar with all that I am doing.

When I open RStudio to do the work, I first run the following two commands:

require("knitr")
require("ggplot2")

I then click on the Compile PDF. I have the following code that throws an error:

<<histogram, echo=FALSE, fig.align='center'>>=
summary(los$hosp_svc)
summary(los$Pt_Age)

binsize = diff(range(los$Pt_Age)/30)
ggplot(los, aes(x = Pt_Age)) + 
  geom_histogram(binwidth = binsize, fill = "red", 
                 alpha = 0.315, colour = 'black') +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank()) +
  xlab("Patient Age in Years") +
  ylab("Frequency/Count") +
  ggtitle("Histogram of Patient Age")
@

The error that I am getting is that the ggplot function could not be found, which is odd because if I just run the above code in the console the graph produces just find, so I know the package is loaded and available for use.

Any thoughts?

Thank you,

Upvotes: 2

Views: 6332

Answers (1)

Benjamin
Benjamin

Reputation: 17369

When working with .Rnw files (or .Rmd files), be sure to include any library calls in your script (see below). When you press the "Compile PDF" button, the R code in your script is submitted to a new instance of R to prevent anything in your current environment from mucking up the results. This might seem a little strange, but is good for reproducibility. So objects that aren't created explicitly via your script and packages that aren't called explicitly in your script will be forgotten as soon as you hit "Compile PDF"

<<histogram, echo=FALSE, fig.align='center'>>= 
library(ggplot2)
summary(los$hosp_svc) 
summary(los$Pt_Age)

binsize = diff(range(los$Pt_Age)/30) 
ggplot(los, aes(x = Pt_Age)) + 
  geom_histogram(binwidth = binsize, 
                 fill = "red", 
                 alpha = 0.315, 
                 colour = 'black') + 
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank()) + 
  xlab("Patient Age in Years") + 
  ylab("Frequency/Count") + 
  ggtitle("Histogram of Patient Age") 
@

Upvotes: 7

Related Questions