Python 带有多个颜色条的二维直方图

Python 带有多个颜色条的二维直方图,python,numpy,histogram,heatmap,contour,Python,Numpy,Histogram,Heatmap,Contour,我有3个数据集,我想在同一个二维平面上显示。因为使用seaborn的kdeplot时会有点拥挤,所以我想使用一些热图。在python中,是否可以使用3个不同的颜色条(每个数据集一个)或一个复合颜色条创建单个2D直方图或热图?这是一个轮廓的例子 import numpy as np import matplotlib.pyplot as plt import seaborn as sns x1, x2, x3 = np.random.normal(0.2, 0.1, 100), np.rando

我有3个数据集,我想在同一个二维平面上显示。因为使用seaborn的kdeplot时会有点拥挤,所以我想使用一些热图。在python中,是否可以使用3个不同的颜色条(每个数据集一个)或一个复合颜色条创建单个2D直方图或热图?这是一个轮廓的例子

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

x1, x2, x3 = np.random.normal(0.2, 0.1, 100), np.random.normal(0.7, 0.1, 100), np.random.normal(0.5, 0.1, 100)
y1, y2, y3 = np.random.normal(0.2, 0.1, 100), np.random.normal(0.2, 0.1, 100), np.random.normal(0.5, 0.1, 100)
plt.figure()
sns.kdeplot(x1, y1, color="blue")
sns.kdeplot(x2, y2, color='green')
sns.kdeplot(x3, y3, color="red")

plt.show()

在我看来,它是一个白色或黑色的平面,不同的数据集有红色、绿色和蓝色的热点,但我不知道如何重叠这些类型的热图,例如plt.hist2d()或plt.hexbin()或plt.imshow()。我已经定义了一个我认为有用的自定义颜色映射,但是我不确定如何将不同的数据集分配给映射的主颜色

cmap2 = ["white", "blue", "green", "red"]
cmap2_arr = np.array([list(mpl.colors.to_rgba(c)) for c in cmap2])  # This converts the names to rgba tuples
map_object = mpl.colors.LinearSegmentedColormap.from_list(name='mymap', colors=cmap2_arr)
plt.register_cmap(cmap=map_object)

您可以尝试在3D中绘制数据的2D等高线图,如下所示

from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches

fig    = plt.figure()
ax     = fig.add_subplot(projection='3d')

x      = np.linspace(0, 1, 100)
X, Y   = np.meshgrid(x, x)
levels = np.linspace(-0.1, 0.4, 100)  #(z_min,z_max,number of contour),

x1, x2, x3 = np.random.normal(0.2, 0.1, 100), np.random.normal(0.7, 0.1, 100), np.random.normal(0.5, 0.1, 100)

y1, y2, y3 = np.random.normal(0.2, 0.1, 100), np.random.normal(0.7, 0.1, 100), np.random.normal(0.5, 0.1, 100)

a=0
b=1
c=2

def f(a, b):
   return np.sin(a*X)*np.sin(b*Y)

Z1 = a + f(2, 4)
Z2 = b + f(3, 4)
Z3 = c + f(4, 5)

# following is for changing default cmap
# value in plt.contourf
# cmap = plt.get_cmap('inferno')

plt.contourf(x1, y1, Z1, levels=a+levels)
plt.contourf(x2, y2, Z2, levels=b+levels)
plt.contourf(x3, y3, Z3, levels=c+levels)

plt.colorbar()
plt.show()

一些有用的参考资料