原文:https://mp.weixin.qq.com/s/BK-i9XcP4n3wZ1ipBV_5nQ
1 matplotlib は散布密度プロットを描画します
散乱密度は主にサンプル点の出現数、つまり密度を計算します。
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
# Generate fake data
N=1000
x = np.random.normal(size=N)
y = x * 3 + np.random.normal(size=N)
# Calculate the point density
xy = np.vstack([x,y]) # 将两个维度的数据叠加
z = gaussian_kde(xy)(xy) # 建立概率密度分布,并计算每个样本点的概率密度
# Sort the points by density, so that the densest points are plotted last
idx = z.argsort()
x, y, z = x[idx], y[idx], z[idx]
fig, ax = plt.subplots()
plt.scatter(x, y,c=z, s=20,cmap='Spectral') # c表示标记的颜色
plt.colorbar()
plt.show()
スキャッターで使用できる他の cmap については、[https://matplotlib.org/tutorials/colors/colormaps.html] を参照してください。
カラーバーは、色の名前の後に逆順に追加されます_r
。例: cmap='Spectral_r'
。
2 seaborn は散布密度プロットを描画します
import seaborn as sns
sns.kdeplot(x=x, y=y, fill=True, cmap='Spectral', cbar=True)
3 mpl 散乱密度包
# !pip install mpl-scatter-density
import mpl_scatter_density
N=100000
x = np.random.normal(size=N)
y = x * 3 + np.random.normal(size=N)
# 绘制二维散点密度图
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='scatter_density')
density = ax.scatter_density(x, y, cmap='Spectral_r')
ax.set_xlim(-3, 3)
ax.set_ylim(-10, 10)
fig.colorbar(density, label='Number of points per pixel')
fig.savefig('gaussian.png')
このパッケージを使用して描画したグラフのゼロ値には色が付いていますが、以下の方法でゼロ値を白くすることができます。
import matplotlib.colors as mcolors
norm = mcolors.TwoSlopeNorm(vmin=-1, vmax =60, vcenter=0)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='scatter_density')
density = ax.scatter_density(x, y,norm=norm, cmap=plt.cm.RdBu)
ax.set_xlim(-3, 3)
ax.set_ylim(-10, 10)
fig.colorbar(density, label='Number of points per pixel')
fig.savefig('gaussian_color_coded.png')
上記の方法ではゼロ値を白くすることはできますが、あまり美しくないので、ゼロ値をマスクしたり、 に代入したりすることができますnan
。ソース コードbase_image_artist.py
のmake_image
関数 (行180 ) に次のステートメントを追加します。
array = np.where(array>0, array, np.nan)
# 或者
array = np.ma.masked_array(array, mask=(array<=0))
このパッケージはfast_histogram
計算サンプル周波数を呼び出します。
from fast_histogram import histogram2d
ymin, ymax = y.min(), y.max()
xmin, xmax = x.min(), x.max()
array = histogram2d(y, x, bins=10,range=((ymin, ymax), (xmin, xmax)))
参考:
https://www.cnblogs.com/niuniu238/p/14128661.html