7 Including Stata Graphs
Including Stata graphics in your Statamarkdown document is fairly simple, but it is not automatic.
There are fundamentally two approaches you can take to include a Stata graph in your document. For both, you must first issue the Stata command(s) to create and save your graph.
Then, separately, indicate where the image is to be placed in your document.
7.1 Saving a Stata Graph
In Stata you use two commands to create and save
your graph. Breaking it into two commands is necessary
to save a graph in a format that can be included in a document.
It also makes it easy to reduce the
clutter for your readers. For example, use the echo=1
chunk option to show your
reader only the scatter
command in the following code block.
```{stata scatterplot, echo=1, results="hide"}
scatter mpg weight
quietly graph export scatter.svg, replace
```
Your options for graphics file formats depend upon your operating system, the version of Stata you are using, and the output format for your final document.
Common formats for HTML documents are png, jpg, and svg. Common formats for PDF documents are png, jpg, and pdf.
7.2 Insert via Markdown (for HTML or PDF documents)
In Markdown, you can link to separate image files from within your document.
(Keep in mind that when you publish an HTML document with a linked graph file, you need to publish both files.)
The Markdown specification allows you to insert a graphics file in the following manner
![Mileage ~ Weight](scatter.svg)
(In a PDF document, the graph may float to a different position, or even the next page.)
7.3 Insert SVG via R (HTML)
SVG is a graphics format that saves information as text in a form that many programs, including web browsers recognize and render appropriately. For files of this type, the SVG code can be included directly in an HTML document.
The following code chunk reads the contents of an SVG file into a Markdown document. This can be used to include graphics within you main HTML file, simplifying file management later.
The R code here also deletes the graphics file after it has been used in your document.
```{r graphincl, echo=FALSE, results="asis"}
cat(readLines("scatter.svg"))
```
```{r cleanup, include=FALSE}
unlink("scatter.svg")
```
Notice that this method does not give you a figure caption, nor does it center your graph on the page.