Scatterplot Matrix in ggplot2
How to make Scatterplot Matrix using `ggpairs()` in ggplot2 with Plotly.
New to Plotly?
Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.
Default splot plot
The ggpairs()
function of the GGally
package allows to build a great scatterplot matrix.
Scatterplots of each pair of numeric variable are drawn on the left part of the figure. Pearson correlation is displayed on the right. Variable distribution is available on the diagonal.
library(plotly)
library(GGally)
data <- data.frame( var1 = 1:100 + rnorm(100,sd=20), v2 = 1:100 + rnorm(100,sd=27), v3 = rep(1, 100) + rnorm(100, sd = 1))
data$v4 = data$var1 ** 2
data$v5 = -(data$var1 ** 2)
p <- ggpairs(data, title="correlogram with ggpairs()")
ggplotly(p)
Visualize correlation
he ggcorr()
function allows to visualize the correlation of each pair of variable as a square. Note that the method
argument allows to pick the correlation type you desire.
library(plotly)
library(GGally)
data <- data.frame( var1 = 1:100 + rnorm(100,sd=20), v2 = 1:100 + rnorm(100,sd=27), v3 = rep(1, 100) + rnorm(100, sd = 1))
data$v4 = data$var1 ** 2
data$v5 = -(data$var1 ** 2)
p <- ggcorr(data, method = c("everything", "pearson"))
ggplotly(p)
Split by group
It is possible to use ggplot2
aesthetics on the chart, for instance to color each category.
library(plotly)
library(GGally)
data(flea)
p <- ggpairs(flea, columns = 2:4, ggplot2::aes(colour=species))
ggplotly(p)
Change plot types
Change the type of plot used on each part of the correlogram
. This is done with the upper
and lower
argument.
library(plotly)
library(GGally)
data(tips, package = "reshape")
p <- ggpairs(
tips[, c(1, 3, 4, 2)],
upper = list(continuous = "density", combo = "box_no_facet"),
lower = list(continuous = "points", combo = "dot_no_facet")
)
ggplotly(p)
What About Dash?
Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
Learn about how to install Dash for R at https://dashr.plot.ly/installation.
Everywhere in this page that you see fig
, you can display the same figure in a Dash for R application by passing it to the figure
argument of the Graph
component from the built-in dashCoreComponents
package like this:
library(plotly)
fig <- plot_ly()
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... )
library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)
app <- Dash$new()
app$layout(
htmlDiv(
list(
dccGraph(figure=fig)
)
)
)
app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)