带圆圈的热图指示人口规模

BKS*_*BKS 8 python data-visualization matplotlib seaborn

嗨,我想用 Python 生成一个热图,类似于所示的热图,其中圆圈的大小表示该单元格中样本的大小。我查看了 seaborn 的画廊并找不到任何东西,而且我认为我无法用 matplotlib 做到这一点。

示例热图

小智 14

这是相反的。虽然 matplotlib 几乎可以做任何事情,但 seaborn 只提供了一小部分选项。因此,使用 matplotlib,您可以绘制一个PatchCollection圆圈,如下所示。
注意:您同样可以使用散点图,但由于散点大小是绝对单位,因此很难将它们缩放到网格中。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection

N = 10
M = 11
ylabels = ["".join(np.random.choice(list("PQRSTUVXYZ"), size=7)) for _ in range(N)]
xlabels = ["".join(np.random.choice(list("ABCDE"), size=3)) for _ in range(M)]

x, y = np.meshgrid(np.arange(M), np.arange(N))
s = np.random.randint(0, 180, size=(N,M))
c = np.random.rand(N, M)-0.5

fig, ax = plt.subplots()

R = s/s.max()/2
circles = [plt.Circle((j,i), radius=r) for r, j, i in zip(R.flat, x.flat, y.flat)]
col = PatchCollection(circles, array=c.flatten(), cmap="RdYlGn")
ax.add_collection(col)

ax.set(xticks=np.arange(M), yticks=np.arange(N),
       xticklabels=xlabels, yticklabels=ylabels)
ax.set_xticks(np.arange(M+1)-0.5, minor=True)
ax.set_yticks(np.arange(N+1)-0.5, minor=True)
ax.grid(which='minor')

fig.colorbar(col)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明