Is there a simple way to get log transformed counts when plotting a two dimensional histogram in matplotlib? Unlike the pyplot.hist
method, the pyplot.hist2d
method does not seem to have a log parameter.
Currently I'm doing the following:
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
matrix, *opt = np.histogram2d(x, y)
img = plt.imshow(matrix, norm = mpl.colors.LogNorm(), cmap = mpl.cm.gray,
interpolation="None")
Which plots the expected histogram, but the axis labels show the indices of the bins and thus not the expected value.
To display the count over the bar in matplotlib histogram, we can iterate each patch and use text() method to place the values over the patches.
The method yscale() or xscale() takes a single value as a parameter which is the type of conversion of the scale, to convert axes to logarithmic scale we pass the “log” keyword or the matplotlib. scale. LogScale class to the yscale or xscale method.
hist2d() Function. The hist2d() function in pyplot module of matplotlib library is used to make a 2D histogram plot. Syntax:matplotlib.pyplot.hist2d(x, y, bins=10, range=None, density=False, weights=None, cmin=None, cmax=None, \*, data=None, \*\*kwargs)
The logarithmic scale in Matplotlib The scale means the graduations or tick marks along an axis. They can be any of: matplotlib. scale. LinearScale—These are just numbers, like 1, 2, 3.
It's kind of embarrassing, but the answer to my question is actually in the docstring
of the corresponding code:
Notes
-----
Rendering the histogram with a logarithmic color scale is
accomplished by passing a :class:`colors.LogNorm` instance to
the *norm* keyword argument. Likewise, power-law normalization
(similar in effect to gamma correction) can be accomplished with
:class:`colors.PowerNorm`.
So this works:
import matplotlib as mpl
import matplotlib.pylab as plt
par = plt.hist2d(x, y, norm=mpl.colors.LogNorm(), cmap=mpl.cm.gray)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With