Show Sidebar Hide Sidebar

2D Histograms in Python

How to make 2D Histograms in Python with Plotly.

New to Plotly?Â¶

You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version CheckÂ¶

Note: 2D Histograms are available in version 1.9.12+
Run pip install plotly --upgrade to update your Plotly version

In [1]:
import plotly
plotly.__version__

Out[1]:
'2.0.2'

2D Histogram with Slider ControlÂ¶

Add slider controls to 2d histograms with the postMessage API.
See the code on JSFiddle.
Watch the 5 second video of how it works.

In [2]:
from IPython.core.display import display,HTML
display(HTML('<iframe height=600 width=950 src="https://jsfiddle.net/plotlygraphs/y9sdy76h/4/embedded/result,js,html/"></iframe>'))


2D Histogram of a Bivariate Normal DistributionÂ¶

In [3]:
import plotly.plotly as py
import plotly.graph_objs as go

import numpy as np

x = np.random.randn(500)
y = np.random.randn(500)+1

data = [
go.Histogram2d(
x=x,
y=y
)
]
py.iplot(data)

Out[3]:

2D Histogram Binning and Styling OptionsÂ¶

In [4]:
import plotly.plotly as py
import plotly.graph_objs as go

import numpy as np

x = np.random.randn(500)
y = np.random.randn(500)+1

data = [
go.Histogram2d(x=x, y=y, histnorm='probability',
autobinx=False,
xbins=dict(start=-3, end=3, size=0.1),
autobiny=False,
ybins=dict(start=-2.5, end=4, size=0.1),
colorscale=[[0, 'rgb(12,51,131)'], [0.25, 'rgb(10,136,186)'], [0.5, 'rgb(242,211,56)'], [0.75, 'rgb(242,143,56)'], [1, 'rgb(217,30,30)']]
)
]
py.iplot(data)

Out[4]:

2D Histogram Overlaid with a Scatter ChartÂ¶

In [1]:
import plotly.plotly as py
import plotly.graph_objs as go

import numpy as np

x0 = np.random.randn(100)/5. + 0.5  # 5. enforces float division
y0 = np.random.randn(100)/5. + 0.5
x1 = np.random.rand(50)
y1 = np.random.rand(50) + 1.0

x = np.concatenate([x0, x1])
y = np.concatenate([y0, y1])

trace1 = go.Scatter(
x=x0,
y=y0,
mode='markers',
showlegend=False,
marker=dict(
symbol='x',
opacity=0.7,
color='white',
size=8,
line=dict(width=1),
)
)
trace2 = go.Scatter(
x=x1,
y=y1,
mode='markers',
showlegend=False,
marker=dict(
symbol='circle',
opacity=0.7,
color='white',
size=8,
line=dict(width=1),
)
)
trace3 = go.Histogram2d(
x=x,
y=y,
colorscale='YlGnBu',
zmax=10,
nbinsx=14,
nbinsy=14,
zauto=False,
)

layout = go.Layout(
xaxis=dict( ticks='', showgrid=False, zeroline=False, nticks=20 ),
yaxis=dict( ticks='', showgrid=False, zeroline=False, nticks=20 ),
autosize=False,
height=550,
width=550,
hovermode='closest',

)
data = [trace1, trace2, trace3]
fig = go.Figure(data=data, layout=layout)

py.iplot(fig)

Out[1]: