Regression Diagnostic Plots using R and Plotly

Plotly is a platform for making, editing, and sharing customizable and interactive graphs. Embedding Plotly graphs in a R-Markdown document is very easy. Here, we will genarate a R-Markdown document with embedded Plotly charts to visualize regression diagnostic plots similar to the ones generated by using plot() on a fitted lm() object.


First step is to install R-Studio. R-Studio makes it very easy to write R-Markdown documents.

Install Plotly

Run the following command(s) in the console

Start a new R-Markdown document

For an introduction to R-Markdown visit

Function to generate plots

The following code snippet creates a function that accepts a fitted lm() object and returns plotly charts. Paste the following code snippet(s) as chunks in the R-Markdown document as shown.

Create regression model

Let’s create a sample regression model using the mtcars dataset.

Call function

We can simply pass the fitted lm object to the above function.


Note that the function returns a list of four plots. Unlike par(mfrow = c()) we’ll use <div> tags to arrange the four plots in a matrix like layout of 2 rows and 2 columns. Use the fig.width and fig.height chunk options to set appropriate plot width and height. Simply use double square brackets [[]] to refer to each figure and print the same. Or you could use print(). See image below.

The output should look like this:

Further Resources

This post hopefully helps you get started with Ploty and using it in R-Markdown documents. Refer to Plotly’s Figure Reference for more details.