首页 > 解决方案 > 使用 matplotlib 具有等高线热叠加的散点图

问题描述

我有大量数据,其中包括 >200k 的值。

目标是显示数据的分布和粗略趋势,而不是单个点。我想添加一个轮廓热覆盖,类似于这个问题,但使用 matplotlib,并带有指定轮廓数量及其间隔的选项:

https://stats.stackexchange.com/questions/31726/scatterplot-with-contour-heat-overlay

我希望这很清楚。如果没有,请告诉我!

标签: matplotlibscatter-plotcontour

解决方案


Seaborn 的 kdeplot 将允许您仅绘制阴影而不是绘制所有数据点。可以通过指定 n_levels 参数来调整轮廓的数量。对于覆盖关节图和 kdeplot 的较小数据集,允许显示数据点和等高线。人物美学可以有很大的不同,因此我在下面编译了一些不同的选项。带有联合图的子图是使用 ImportanceOfBeingErnest 对这个问题的回答生成的。

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
mean = [0, 0]
cov = [[50, 0], [0, 100]] 
x, y = np.random.multivariate_normal(mean, cov, 5000).T

# For large data sets
plt.subplots(1, 2)
plt.subplot(1, 2, 1)
cmap = sns.cubehelix_palette(as_cmap=True, dark=0, light=1, reverse=True)
a = sns.kdeplot(x, y, n_levels=20, shade=True, cmap=cmap, gridsize=200, cbar=True)
a.set_xlabel('x')
a.set_ylabel('y')
plt.subplot(1, 2, 2)
b = sns.kdeplot(x, y, n_levels=60, shade=True, gridsize=100, cmap="RdBu_r", cbar=True)
b.set_xlabel('x')
b.set_ylabel('y')

在此处输入图像描述

# For smaller data sets - jointplot and kdeplot overlayed. 
# Plain overlay
c = (sns.jointplot(x, y, color="g", marker='.').plot_joint(sns.kdeplot, n_levels=20)).set_axis_labels('x', 'y')
# with shade=True
d = (sns.jointplot(x, y, color="g").plot_joint(sns.kdeplot, n_levels=20, shade=True)).set_axis_labels('x', 'y')
# with transparency control, alpha=
e = (sns.jointplot(x, y, color="g", marker='.').plot_joint(sns.kdeplot, n_levels=20, shade=True, alpha=0.5)).set_axis_labels('x', 'y')
# diverging colour palette - blue to red
f = (sns.jointplot(x, y, marker='.').plot_joint(sns.kdeplot, n_levels=20, cmap="RdBu_r")).set_axis_labels('x', 'y')
# diverging colour palette and shade and reg
g = (sns.jointplot(x, y, marker='.', kind='reg').plot_joint(sns.kdeplot, n_levels=20, cmap="RdBu_r")).set_axis_labels('x', 'y')
# diverging colour palette, shade, 
h = (sns.jointplot(x, y).plot_joint(sns.kdeplot, n_levels=20, shade=True, cmap="RdBu_r")).set_axis_labels('x', 'y')

在此处输入图像描述


推荐阅读