1

I already know how to set the bin size for a 1D histogram after looking at this answer,but I don't know how to do this for a 2D histogram. I have referred to both the Numpy and Matplotlib pages for the 2D histograms, but all my attempts to adjust the bin size did not work/run.I want my bins to have a length of 20 and a width of 2.

Example code:

import numpy as np
import matplotlib.pyplot as plt
import math

dataX = np.random.uniform(-50,50,100)
dataY = np.random.uniform(-50,50,100)

binWidth = 2.0
binLength = 20.0

xMin = min(dataX)
xMax = max(dataX)
yMin = min(dataY)
yMax = max(dataY)

#this and all other similar attempts that I have tried did not run
np.histogram2d(dataX, dataY, bins = np.arange((xMin,xMax + binWidth),(yMin,yMin +binLength),(binWidth,binLength)))

Looking forward to your hints/help/advice.

user3451660
  • 447
  • 8
  • 17
  • Your usage of `np.arange` is wrong. For `hist2d` you can provide an array rather than a tuple: `bins = [x,y]` – Fourier Jun 08 '18 at 08:59

1 Answers1

3

You could do e.g.

plt.hist2d(dataX, dataY, bins = [np.arange(xMin, xMax, binWidth), np.arange(yMin, yMax, binLength)])

bins accepts integers or arrays for defining the number of bins or their edges, each of it either once for both dimensions or in a list with two entries to give two different definietions for x and y.

From the docs:

bins : int or array_like or [int, int] or [array, array], optional

The bin specification:

   If int, the number of bins for the two dimensions (nx=ny=bins).
   If array_like, the bin edges for the two dimensions (x_edges=y_edges=bins).
   If [int, int], the number of bins in each dimension (nx, ny = bins).
   If [array, array], the bin edges in each dimension (x_edges, y_edges = bins).
   A combination [int, array] or [array, int], where int is the number of bins and array is the bin edges.
Community
  • 1
  • 1
SpghttCd
  • 10,510
  • 2
  • 20
  • 25