# How does numpy.histogram2d works in Python

In this tutorial, we will understand what numpy.histogram2d is and how it works in Python. The Numpy library contains many functions which perform mathematical operations with arrays in Python. The histogram2d method generates a bi-directional histogram of two data samples.

### Numpy.histogram2d() method

**Syntax:**

numpy.histogram2d(x, y, bins=10, range=None, normed=None, weights=None, density=None)

**Parameters:**

- x: an array having the x coordinates of the points
- y: an array having the y coordinates of the points
- bins: defines the number of bins or bin edges
- range: gives leftmost and rightmost edges of the bins
- density: if true returns the probability density function at the bin, if false returns the number of samples in each bin
- normed: similar to density argument
- weights: an array of weights

**Returns:**

- H: Bi-dimensional histogram of x and y.
- xedges: Bin edges along the first dimension.
- yedges: Bin edges along the second dimension.

**Example:**

Importing required libraries,

import matplotlib.pyplot as plt import numpy as np

Define the bin edges,

xedges = [0, 2, 3, 6] yedges = [0, 1, 3, 5, 7]

- Create a histogram H,

x = np.random.normal(2, 1, 100) y = np.random.normal(1, 1, 100) H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges)) H = H.T

- Histogram does not follow Cartesian convention, so we transpose H for displaying. We are using ‘
`imshow`

‘ for displaying histograms using square bins,

fig = plt.figure(figsize=(7, 4)) ax = fig.add_subplot(131, title='imshow: square bins') plt.imshow(H, origin='lower')

**Output:**

You may also learn,

## Leave a Reply