Brandon Walker

Data Scientist

Tutorial: ggplot and ggplotly

4 minutes
June 12, 2019

If you want to be considered good at R, it’s best you know ggplot. If you’re using base R graphics I get the impression other data scientists may look at your graphics as childish (though I think there is nothing wrong with using base R). I’ll give a quick walk through of ggplot and making use of ggplotly from the plotly package. We’re going to use the cars data set, which is comes with R so don’t worry about getting it. In this dataset we have speeds a car was going at and how many feet it moved once the brakes were applied before it stopped.

Using ggplot

First load the package which is actually called ggplot2. Use the ggplot() function to make an empty graph, then put in your data as your first argument, and fill in the aesthetics of the graph by providing aes(x = , y = ). Finally to tell ggplot what type of graph you want use + geom_point(), geom_col(), geom_abline() and so on to get exactly what you want. To edit you axis labels just use + labs(x = , y =)

library(ggplot2)

plot <- ggplot(cars, aes(x = speed, y = dist)) + geom_point() + 
    labs(x = "Speed", y = "Stopping Distance")

plot

Using ggplotly

To make any plot interactive add the ggplotly() function around any ggplot object! Working this into an Rmakrdown presentation takes your presentation one step further than powerpoint. It’s also really handy for data exploration. Hover your mouse over the chart to see what this does.

library(plotly)

ggplotly(plot)