Graphics: Interactive Graphs
Prologue
- In Graphics: Annotations, we looked into annotating specific data points. These are data points which you have likely determined in advance before plotting.
- In most instances, you may not know which points you may want to annotate on your plot. An interactive scatterplot would be very useful for exploring data points in a “live” mode as you will see soon. This will enable annotating data points in an ad hoc fashion.
- To do this, we will be using the plotly package.
# Load library
library(plotly)
# Load dataset
data(iris)
# Add ID column
iris2 <- cbind("ID"=c(1:dim(iris)[1]), iris)
head(iris2)
## ID Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 1 5.1 3.5 1.4 0.2 setosa
## 2 2 4.9 3.0 1.4 0.2 setosa
## 3 3 4.7 3.2 1.3 0.2 setosa
## 4 4 4.6 3.1 1.5 0.2 setosa
## 5 5 5.0 3.6 1.4 0.2 setosa
## 6 6 5.4 3.9 1.7 0.4 setosa
Default data labels
- The syntax for plotly differs slightly from that of ggplot2, but not drastically.
- The mode=“markers” argument specifies that a scatterplot should be plotted.
plot_ly(iris2, x=~Sepal.Length, y=~Petal.Length, mode="markers")
## No trace type specified:
## Based on info supplied, a 'scatter' trace seems appropriate.
## Read more about this trace type -> https://plot.ly/r/reference/#scatter
- Hover your cursor over the different data points to observe the corresponding labels.
- Notice that the default data labels indicate the (x,y) coordinates/values.
Customized data labels
- Instead of (x,y) coordinates/values, perhaps data (unique) identifiers or names may be more useful.
- To observe your selected labels in lieu of the default labels, just pass the text argument indicating which columns of your data frame you would like to use as your labels.
plot_ly(iris2, x=~Sepal.Length, y=~Petal.Length, mode="markers", text=~ID)
## No trace type specified:
## Based on info supplied, a 'scatter' trace seems appropriate.
## Read more about this trace type -> https://plot.ly/r/reference/#scatter
- Now that you are able to explore and identify the individual data points, you may want to display the labels of selected data points on your plot.
- Refer to Graphics: Annotations for this purpose.
- Interactive graphics cover a much large scope than what was just described here. Here, we merely exploit the usefulness of interactive graphics for the purpose of ad hoc annotation in scatterplots.