1
1

More than 1 year has passed since last update.

matplotlibの2DヒストグラムでX軸、Y軸、Z軸をログ表示する方法

Last updated at Posted at 2021-09-16

使い所

matplotlib の 2Dヒストグラムで、全軸(X, Y, Z) をログ表示する方法を紹介する。 (横縦軸が log-log の 2dhist で zscale も log の図という意味です。)

注意点

Matplotlib 2D histogram seems transposed によくまとまっているが、

  • plt.hist2d は内部的に numpy.histogram2d を使っており、x, y は直感的な順番と同じ
  • matplotlib always expects y to be the first dimenstion であるため、pcolormesh などは、転置した配列を入れる必要がある。

この違いについては理解しておこう。

pcolormesh を使う方法

# -*- coding: utf-8 -*-
"""2dhist_log_log_log.ipynb
Original file is located at    https://colab.research.google.com/drive/1VGo0WdmmUfxqnLdrWVJ98ZO4rJj0oX58
xscale log, yscale log, zscale log, for 2dhist using pcolormesh
"""

import numpy as np
from matplotlib.colors import LogNorm
import matplotlib.cm as cm
import matplotlib.pyplot as plt

# create sample data
x, y = np.random.exponential(size=(2, 100000))
x = x * 10 + 100
y = y * 2 

plt.figure(figsize =(10, 7))

# create uniform x, y range in a log space. 
xmin = np.log10(x.min())
xmax = np.log10(x.max())
ymin = np.log10(y.min())
ymax = np.log10(y.max())
print(xmin, xmax, ymin, ymax)
xbins = np.logspace(xmin, xmax, 100) # <- make a range from 10**xmin to 10**xmax
ybins = np.logspace(ymin, ymax, 50) # <- make a range from 10**ymin to 10**ymax

# create 2D hist using numpy.histogram2d
counts, _, _ = np.histogram2d(x, y, bins=(xbins, ybins))

# plot 2d hist
pcm = plt.pcolormesh(xbins, ybins, counts.T, norm=LogNorm(vmin=1, vmax=counts.max()), cmap='PuBu_r')
plt.colorbar(pcm)
plt.xscale('log')
plt.yscale('log')
plt.xlim(xmin=xbins[0])
plt.xlim(xmax=xbins[-1])
plt.ylim(ymin=ybins[0])
plt.ylim(ymax=ybins[-1])

生成される図がこちら。

スクリーンショット 2021-10-13 2.04.12.png

コードは、google Colab 上にもあります。

その他

エラーがでないのでわかりにくいのが、plt.pcolormesh を用いるか、ax.pcolormesh を用いるか、設定が不適切な適切な場合、エラーなく表示されてしまうのであるが、log にならなかったり、表示範囲が設定されないことがある。(ax の使い方が適切であれば動くのかもしれない。。)

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1