Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: log transform counts in hist2d

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.

like image 214
cel Avatar asked Apr 26 '14 09:04

cel


People also ask

How do I display the count over the bar in Matplotlib histogram?

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.

How do you change the log scale in Matplotlib?

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.

What is hist2d?

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)

What is logarithmic scale in Matplotlib?

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.


1 Answers

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)
like image 178
cel Avatar answered Sep 20 '22 16:09

cel