Show Sidebar Hide Sidebar

# 2D Histograms in R

How to make a 2D histogram in R. A 2D histogram is a visualization of a bivariate distribution.

### New to Plotly?

Plotly's R library is free and open source!
You can set up Plotly to work in online or offline mode.
We also have a quick-reference cheatsheet (new!) to help you get started!

### Version Check

Version 4 of Plotly's R package is now available!
Check out this post for more information on breaking changes and new features available in this version.

library(plotly)
packageVersion('plotly')

## [1] '4.9.1'


#### Basic 2D Histogram

2D histograms require x/y, but in contrast to heatmaps, z is optional. If z is not provided, binning occurs in the browser (see here for a list of binning options).

# install.packages('mvtnorm')
library(plotly)

s <- matrix(c(1, -.75, -.75, 1), ncol = 2)
obs <- mvtnorm::rmvnorm(500, sigma = s)
p <- plot_ly(x = obs[,1], y = obs[,2])
pp <- subplot(
)

pp


#### Colorscale

If z is not provided, the only way to control coloring is through the colorscale attribute

p <- p %>% add_histogram2d(colorscale = "Blues")

p


#### Z Matrix

If you want more control for the binning algorithm, you can supply a 2D table or matrix to z. In this case, the R package will impose it's colorscale default (and the colors argument can be used to control the colorscale from R):

cnt <- with(diamonds, table(cut, clarity))
p <- plot_ly(diamonds, x = ~cut, y = ~clarity, z = ~cnt) %>%