为 matplotlib Axes.scatter 指定颜色级别?

Specify color levels for matplotlib Axes.scatter?

如果我正在绘制一个散点图,其中的点根据大小进行着色,我可以像在 contour 和 contourf 中那样指定颜色级别吗?

例如我这样做:

from random import randrange
import matplotlib.pyplot as plt

x, t, t  = [], [], []
for x in range(10):
     y.append(randrange(30,45,1))
     x.append(randrange(50,65,1))
     t.append(randrange(0,20,1))

fig = plt.figure()
ax = fig.add_subplot()
scats = ax.scatter(x,y,s=30,c=t, marker = 'o', cmap = "hsv")
plt.show()

这会产生这样的情节:

但是有什么方法可以在散点图中添加 'levels' 类型参数吗?在那里我可以指定我的级别为 [0,4,8,12,16,20] 或什么?

这是一种方法,您的代码中还有多个错误,我已修复:您定义了 t 两次,但根本没有定义 y,您覆盖了 x 与您的循环变量,您应该将其替换为 _,这是 Python 中对于您不会使用的变量的约定。

from random import randrange
import matplotlib.pyplot as plt
import matplotlib as mpl

cmap = plt.cm.hsv
bounds = [0,4,8,12,16,20]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

x, y, t  = [], [], []
for _ in range(10):
    x.append(randrange(30,45,1))
    y.append(randrange(50,65,1))
    t.append(randrange(0,20,1))

fig = plt.figure()
ax = fig.add_subplot()
scats = ax.scatter(x,y,s=30,c=t, marker = 'o', cmap=cmap, norm=norm)
fig.colorbar(scats)
plt.show()