Python中的 Matplotlib.pyplot.hist2d()
Matplotlib是Python中的一个库,它是 NumPy 库的数值数学扩展。 Pyplot是Matplotlib模块的基于状态的接口,它提供了一个类似 MATLAB 的接口。
matplotlib.pyplot.hist2d()函数
matplotlib 库的 pyplot 模块中的hist2d()函数用于制作二维直方图。
Syntax:matplotlib.pyplot.hist2d(x, y, bins=10, range=None, density=False, weights=None, cmin=None, cmax=None, \*, data=None, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
- x, y : These parameter are the sequence of data.
- bins : This parameter is an optional parameter and it contains the integer or sequence or string.
- range : This parameter is an optional parameter and it the lower and upper range of the bins.
- density : This parameter is an optional parameter and it contains the boolean values.
- weights : This parameter is an optional parameter and it is an array of weights, of the same shape as x.
- cmin : This parameter has all bins that has count less than cmin will not be displayed.
- cmax : This parameter has all bins that has count more than cmax will not be displayed.
Returns: This returns the following:
- h :This returns the bi-dimensional histogram of samples x and y.
- xedges :This returns the bin edges along the x axis.
- yedges :This returns the bin edges along the y axis.
- image :This returns the QuadMesh.
下面的示例说明了 matplotlib.pyplot 中的 matplotlib.pyplot.hist2d()函数:
示例 #1:
# Implementation of matplotlib function
from matplotlib import colors
from matplotlib.ticker import PercentFormatter
import numpy as np
import matplotlib.pyplot as plt
N_points = 100000
x = np.random.randn(N_points)
y = 4 * x + np.random.randn(100000) + 50
plt.hist2d(x, y,
bins = 100,
norm = colors.LogNorm(),
cmap ="gray")
plt.title('matplotlib.pyplot.hist2d() function \
Example\n\n', fontweight ="bold")
plt.show()
输出:
示例 #2:
#Implementation of matplotlib function
from matplotlib import colors
import numpy as np
from numpy.random import multivariate_normal
import matplotlib.pyplot as plt
result = np.vstack([
multivariate_normal([10, 10],
[[3, 2], [2, 3]], size=1000000),
multivariate_normal([30, 20],
[[2, 3], [1, 3]], size=100000)
])
plt.hist2d(result[:, 0],
result[:, 1],
bins = 100,
cmap = "Greens",
norm = colors.LogNorm())
plt.title('matplotlib.pyplot.hist2d function \
Example')
plt.show()
plt.hist2d(result[:, 0],
result[:, 1],
bins = 100,
cmap = "RdYlGn_r",
norm = colors.LogNorm())
plt.show()
输出: