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!
Get started by downloading the client and reading the primer.
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.

## [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')

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(
  p %>% add_markers(alpha = 0.2),
  p %>% add_histogram2d()



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

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


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) %>%