首页 > 解决方案 > 更改绘图内每个元素的绘图标记

问题描述

我有一个矩阵,我正在使用散点图来可视化它的大小为 800x2。我正在尝试更改每 100 个元素的标记类型,例如从 0 到 99 个标记将是“x”,从 100 到 199 个标记将是“o”等等。

但是我收到以下错误:

TypeError:只有整数标量数组可以转换为标量索引

这是我的实际代码:

from matplotlib.pyplot import figure
import numpy as np
color=['b','r'] 
markers = ['x', 'o', '1', '.', '2', '>', 'D', 'v'] 
X_lda_colors=  [ color[i] for i in list(np.array(y)%8) ] 
X_lda_markers= [ markers[i] for i in list(np.array(y)%2) ] 
plt.xlabel('1-eigenvector')
plt.ylabel('2-eigenvector')

for i in range(X_lda.shape[0]):
    plt.scatter( 
        X_lda[i,0],    
        X_lda[i,1],    
        c=X_lda_colors[i],
        marker=X_lda_markers[i],    
        cmap='rainbow',   
        alpha=0.7,     
        edgecolors='w')
plt.show()

我的目标是基本上使用任何类型的标记来区分我的 x_lda[i, 1] 标签内的每 100 个元素,这些元素是正在绘制的集群。此代码用于遵循以下问题:Plotting different clusters markers for each class in scatter plot

但就我而言,它给了我上述错误。

这是一个可重现的示例:

X_lda = np.asarray([([1, 2], [1,5], [2, 3],[3, 5], [3, 4], [6, 9], [7, 9], [7, 8], [7, 10], [7, 12], [13, 14], [15, 16], [12, 14], [13, 15], [12, 14], [14, 14], [13, 4], [12, 5], [13, 4], [13, 3], [12, 6])]).reshape(21, 2)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
from matplotlib.pyplot import figure
plt.xlabel('LD1')
plt.ylabel('LD2')
plt.scatter(
    X_lda[:,0],
    X_lda[:,1],
    c=['red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'green', 'green', 'green', 'green', 'green', 'green', 'green', 'green', 'green', 'green', 'green'],
    cmap='rainbow',
    alpha=0.7,
    edgecolors='w'
)

例如,对于这个 21x2 数组,我想将前 7 个元素更改为“x”,接下来的 7 个元素更改为“o”,最后 7 个元素更改为“>”。

标签: pythonpython-3.xmatplotlibcluster-analysisscatter-plot

解决方案


我认为您可能正在寻找类似的东西,在上面的代码中交换第 5 行和第 6 行:

X_lda_colors=  [ color[i%2]   for i in range(X_lda.shape[0])  ] 
X_lda_markers= [ markers[i%8] for i in range(X_lda.shape[0])  ] 

但是,您不应循环遍历所有 800 个点并分别创建一个图。解决方法是这样的:

# plot each point in blue
plt.scatter(
    X_lda[:,0], X_lda[:,1]
    c = "b",
    ...
)

# plot again using every 100th element in red
plt.scatter(
    X_lda[::100,0], X_lda[::100,1]
    c = "r",
    ...
)

这将用第二个红色点叠印第 100 个元素。您最终只有两个分别具有 800 点和 8 点的绘图对象。


推荐阅读