python - Creating a log-linear plot in matplotlib using hist2d -


i wondering if can done. have tried set bins explicitly using numpy logspace, , have tried set xscale 'log'. neither of these options work. has ever tried this?

i want 2d histogram log x-axis , linear y-axis.

the reason it's not working correctly plt.hist2d uses pcolorfast method, more efficient large images, doesn't support log axes.

to have 2d histogram works correctly on log axes, you'll need make using np.histogram2d , ax.pcolor. however, it's 1 line of code.

to start with, let's use exponentially spaced bins on linear axis:

import numpy np import matplotlib.pyplot plt  x, y = np.random.random((2, 1000)) x = 10**x  xbins = 10**np.linspace(0, 1, 10) ybins = np.linspace(0, 1, 10)  fig, ax = plt.subplots() ax.hist2d(x, y, bins=(xbins, ybins))  plt.show() 

enter image description here

okay, , good. let's see happens if make x-axis use log scale:

import numpy np import matplotlib.pyplot plt  x, y = np.random.random((2, 1000)) x = 10**x  xbins = 10**np.linspace(0, 1, 10) ybins = np.linspace(0, 1, 10)  fig, ax = plt.subplots() ax.hist2d(x, y, bins=(xbins, ybins))  ax.set_xscale('log') # <-- difference previous example  plt.show() 

enter image description here

notice log scaling seems have been applied, colored image (the histogram) isn't reflecting it. bins should appear square! they're not because artist created pcolorfast doesn't support log axes.

to fix this, let's make histogram using np.histogram2d (what plt.hist2d uses behind-the-scenes), , plot using pcolormesh (or pcolor), support log axes:

import numpy np import matplotlib.pyplot plt np.random.seed(1977)  x, y = np.random.random((2, 1000)) x = 10**x  xbins = 10**np.linspace(0, 1, 10) ybins = np.linspace(0, 1, 10)  counts, _, _ = np.histogram2d(x, y, bins=(xbins, ybins))  fig, ax = plt.subplots() ax.pcolormesh(xbins, ybins, counts.t)  ax.set_xscale('log')  plt.show() 

(note have transpose counts here, because pcolormesh expects axes in order of (y, x).)

now result we'd expect:

enter image description here


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -