原文: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()

scatter中其他可使用的cmap,参考【https://matplotlib.org/tutorials/colors/colormaps.html】

colorbar反向在颜色名称后面加_r,比如:cmap='Spectral_r'

2 seaborn绘制散点密度图

import seaborn as sns
sns.kdeplot(x=x, y=y, fill=True, cmap='Spectral', cbar=True)
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))
最初遇到这个问题的时候,找到的大答案是绘制contour,比如:
http://stackoverflow.com/questions/24119920/how-to-plot-a-density-map-in-python?rq=1​
这当然很漂亮,但是这需要有三列数字来标示一个平面;但其实我的问题是仅有两列数的时候如何标示密度:
方法一,使用hist2d:
				
mpl-scatter-density: 使用 matplotlib 创建散点密度可视化 去发现同类优质开源项目:https://gitcode.com/ 是一个 Python 库,它为 matplotlib 提供了一种简单的方法,用于创建具有密度可视化的高质量散点。 什么是 mpl-scatter-density? mpl-scatter-density 是一个轻量级库,它可以让你轻松地在...
散点进行密度统计并画出其相应的热力,主要使用两个函数,一个是histcounts2和imagesc两个函数,下面我们依次进行说明。 histcounts2的具体用法详见:https://ww2.mathworks.cn/help/matlab/ref/histcounts2.html?searchHighlight=histcounts2&s_tid=srchtitle 虽然官网有很多说明,但是不够实用。 要说明的主要是利用histcounts2得到的二维矩阵,其不能直接用imagesc或
头大,外行人做个咋这么难,趋势线还没有研究出来怎么加上去,哎 import matplotlib.pyplot as plt from scipy.stats import gaussian_kde from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import pandas as pd from dbfread import DBF data=DBF('native9.dbf')#数据量超级超级大,e
在这个例子中,我们使用 seaborn 库加载了一个名为 "tips" 的数据集,并使用 `jointplot()` 函数绘制了一个散点密度。其中,x 轴表示账单金额(total_bill),y 轴表示小费金额(tip),kind 参数指定了绘类型为 "kde",即绘制散点密度。 你可以根据自己的需求,调整数据集和绘参数来创建不同类型的散点密度