首页 > 解决方案 > 在python 3中使用matplotlib散点函数时如何更改点子集的绘图标记

问题描述

我有许多自定义的 2d 点对象,每个对象都有:

问题是许多点将共享一个标签 1° 值,但标签 2° 一可能不同,反之亦然。

我尝试提取关于标签 2° 值的点并分别绘制它们,这样:

pointsSubset1 = getPointsWithLabel2Value1()
pointsSubset2 = getPointsWithLabel2Value2()
pointsSubset3 = getPointsWithLabel2Value3()

# just assume x y and labels values are obtained correctly

plt.scatter(x1, y1, c=listOfLabels1ForSubset1, cmap="nipy_spectral", marker='s') # plotting pointsSubset1

plt.scatter(x2, y2, c=listOfLabels1ForSubset2, cmap="nipy_spectral", marker='.') # plotting pointsSubset2

plt.scatter(x3, y3, c=listOfLabels1ForSubset3, cmap="nipy_spectral", marker='<') # plotting pointsSubset3

我认为这会奏效,但事实并非如此。标记设置正确,但颜色设置不正确......

忽略 x 和 y 坐标的示例:

在这种情况下,来自子集 1 的点 1 将与来自子集 2 的点 2 具有不同的标记,但两者将共享相同的颜色(黑色),因为当两者分别绘制时,尽管它们具有不同的 label1 值,但两者都将映射到第一个颜色频谱....

我希望 cmap 中的颜色索引在点子集之间匹配,并且我不认为传递自定义颜色数组是解决方案 bc 标签 1 的可能值在 [-1, +inf] 的范围内(我不'不知道如何管理 cmap 规范化)。

提前致谢。

标签: pythonpython-3.xmatplotlibplotscatter

解决方案


我想会到达你想要的地方

Npoints = 50
x,y = np.random.random(size=(2,Npoints))
label1 = np.random.choice([-1,1,2,3], size=(Npoints,))
label2 = np.random.choice([1,2,3],size=(Npoints,))

label1_min = min(label1)
label1_max = max(label1)
marker_dict = {1:'s',2:'o',3:'<'}

fig, ax = plt.subplots()
for i,m in marker_dict.items():
    ax.scatter(x[label2==i], y[label2==i], marker=m, c=label1[label2==i], cmap='nipy_spectral', vmin=label1_min, vmax=label1_max)

在此处输入图像描述


推荐阅读