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.

library(plotly)
packageVersion('plotly')
## [1] '4.5.2'

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

# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
# chart_link = plotly_POST(pp, filename="histogram2d/basic")
# chart_link

Colorscale

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

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

# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
# chart_link = plotly_POST(p, filename="histogram2d/colorscale")
# chart_link

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

# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
# chart_link = plotly_POST(p, filename="histogram2d/no-binning")
# chart_link
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.