Function not generating figures in rendered HTML output

rmarkdown
rstudio

#1

Hello colleagues,
I am preparing a report in R markdown. To avoid repetitive coding, I am learning how to use functions to plot figures using ggplot().

First, I created a function;

{r, Helper functions}

##First function compares the population trend across genders


line_graph_gender <- function(data_new,xnew,ynew,titlenew,SEX,lwdnew,ylab)
  {
  line_graph_gender <- ggplot(data=data_new,aes(x=xnew,y=ynew,color=SEX))+
  geom_line(lwd=lwdnew)+
  labs(title=titlenew, y=ylab)
  
  return (line_graph_gender)
}

Next, this function was called in a different chunk;

{r, ref.label="Helper functions"}
line_graph_gender(population_projected_gender,population_projected_gender$YEAR, 
 population_projected_gender$gender_pop,"Projected Population as Per Gender from  
 July 1, 2012 through July 1,2060",population_projected_gender$SEX,2,"Population  
 Percent")

In the Rstudio environment, we can see the figure. But, when we generate the HTML output, we don't see that figure in the HTML file.Can I kindly get advice/help in this context?

Help is appreciated.


#2

I'm not entirely sure what you mean when you say you can see the figure in the RStudio environment? However, I can say why your plot doesn't print when you knit the document. Your function is creating a plot object, but it's not printing that object. You can either explicitly call print(line_graph_gender(...)), or you can just remove the assignment inside the function:

line_graph_gender <- function(data_new, xnew, ynew, titlenew, SEX, lwdnew, ylab) {
  ggplot(data = data_new, aes(x = xnew, y = ynew, color = SEX)) +
  geom_line(lwd = lwdnew) +
  labs(title = titlenew, y = ylab)
  
  # This line is unnecessary, since a function automatically returns
  # the result of the last line (in this case, the call to ggplot())
  # return (line_graph_gender)
}

A few notes:

  • If xnew, ynew, and SEX are variables in your data frame data_new, then there's no need to pass them into your function. All you need to pass in is data_new and then you can reference any of its variables inside your ggplot code as you normally would.
  • You don't need to include the ref.label option in your second chunk. Any functions defined in previous chunks are automatically in the global environment and therefore available to any subsequent chunks.
  • Have you seen this guide? Programming with ggplot2

#3

Thank you for your assistance. Moreover, thanks for the link to the guide. It seems a gem worth reading.