python - matplotlib 散点图是否有 'levels' 等效参数?

标签 python matplotlib

我希望在模型输出(填充轮廓)之上绘制观察结果(散点图)。为了突出显示等值线图中感兴趣的区域,我使用 levels 参数指定色标间隔。然而,当我在顶部绘制散点图时,色阶是不同的。有没有办法使散点色标与轮廓色标对齐?

在下面的示例中,我希望点颜色与背景颜色匹配:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0,10).tolist()
y = np.arange(0,10).tolist()
z = np.ndarray((len(x),len(y)))

for i in range(0,10):
    for j in range(0,10):
        z[i][j] = x[i]*7+y[j]*3

im = plt.contourf(z, levels=[0,10,20,30,800,900,1000], cmap='rainbow')
cbar = plt.colorbar(im)
plt.scatter(np.meshgrid(x,y)[0], np.meshgrid(x,y)[1], 
            c=z, cmap='rainbow', edgecolor='k', s=100)

输出:output

最佳答案

Matplotlib 的 contourf 似乎有一种非常奇特的方式来决定其颜色分配(可能可以追溯到 BoundaryNorm 和相关函数之前)。

尽管如此,可以使用从 contourf 结果信息中提取的 ListedColormapBoundaryNorm 来复制该行为。

这是一个稍微修改过的示例:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm, ListedColormap

x = np.arange(0, 10)
y = np.arange(0, 10)
z = x.reshape(1, -1) * 70 + y.reshape(-1, 1) * 30
z[:, 5] = 1000

levels = [0, 10, 20, 30, 800, 900, 1000]
im = plt.contourf(x, y, z, levels=levels, cmap='rainbow')
cbar1 = plt.colorbar(im, pad=0.05)
cbar1.ax.set_title('contourf')

cmap = ListedColormap(im.get_cmap()(im.norm(im.cvalues)))
norm = BoundaryNorm(levels, len(levels) - 1)
sc = plt.scatter(np.meshgrid(x, y)[0], np.meshgrid(x, y)[1],
                 c=z.ravel(), cmap=cmap, norm=norm, edgecolor='k', s=100)
cbar2 = plt.colorbar(sc, pad=0.1)
cbar2.ax.set_title('scatter')

plt.show()

colormap from contourf for scatterplot

关于python - matplotlib 散点图是否有 'levels' 等效参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67165115/

相关文章:

python - 在 pcolormesh 数据上绘制等高线

python - 在 Redshift 查询中转义引号

python - 有效检测大图像中的形状

python - plt.subplots() 中的轴是一个 "numpy.ndarray"对象并且没有属性 "plot"

python - 在 seaborn 中订购箱线图 x 轴

python - PyGame: Sprite 不会移动

python - 在 Python 中比较数据库中的纬度/经度值

python - 为什么线性回归图不正确?提供代码和图片

python - 如何调整 seaborn pairplot 中的透明度(alpha)?

python - 当数据不是周期性的时,如何绘制基于堆叠的条形图