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.

sysuse auto, clear

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.

scatter mpg weight

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)
Mileage ~ Weight
Mileage ~ Weight

(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"}
```{r cleanup, include=FALSE}

Notice that this method does not give you a figure caption, nor does it center your graph on the page.

Stata Graph - Graph 10 20 30 40 Mileage (mpg) 2,000 3,000 4,000 5,000 Weight (lbs.)

7.4 Stata Graph Options

Neither method of including a Stata graph gives you control over graph size or graph aesthetics. These are all elements that must be specified in Stata, rather than R or Statamarkdown.

This page was written using:

  • Statamarkdown version 0.9.2
  • knitr version 1.45