【问题标题】:Changing plot marker for every element inside the plot更改绘图内每个元素的绘图标记
【发布时间】:2020-12-01 08:51:54
【问题描述】:

我有一个矩阵,我使用散点图将其可视化,大小为 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 every 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 个元素更改为“>”。

【问题讨论】:

  • 也许color[i] for i in list(np.array(y)%8) 应该是%2 因为color 只包含2 个元素?

标签: python python-3.x matplotlib cluster-analysis scatter-plot


【解决方案1】:

我认为您可能正在寻找类似的东西,在上面的代码中交换第 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 点的绘图对象。

【讨论】:

  • 好吧,它所做的只是为一半的点添加一个红色 X,这不是最佳的
猜你喜欢
  • 2012-10-16
  • 2013-09-08
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
相关资源
最近更新 更多