将附加信息与Scatterplot点相关的问题

时间:2015-11-05 15:07:59

标签: python matplotlib plot

我正在尝试使用PCA降低数据集的维度。然后我根据一些标准(取决于绘制数据点的文件名的数量)为每个数据点分配一个“类/类别”,并将所有内容绘制为带有遗留的散点图

在每个数据点的另一个列表中,我存储了一些附加信息,我希望每个数据点都是可选择的,这样我就可以在终端中读取有关它的信息。 在绘制我的散点图时 - 我假设因为我按子集方式绘图 - 顺序搞砸了。 接收到的事件的指示不再适合阵列到阵列的附加信息。

我试图在绘图时重新排序信息数组,但不知怎的,它仍然不起作用。这是我的代码:

targets = []
trainNames = []

# React on to a click on a datapoint.
def onPick(event):
  indexes = event.ind
  xy = event.artist.get_offsets()
  for index in indexes:
    print trainNames[index]


# Load the additonal information for each datapoint. It's stored in the
# same order as the datapoints in 'trainingfile.csv'.
modelNamesFile = open("training-names.csv") 
for line in modelNamesFile:

  # Save target for datapoint. It's the class of the object, seperated
  # into "rectangular", "cylindrical", "irregular", dependend on the
  # objects file number.
  objnum = int(line.split(",")[-1].split("/")[-1].split(".")[0])
  if (objnum <= 16):
    objnum = 0
  elif (objnum >= 17 and objnum <= 34):
    objnum = 1
  else:
    objnum = 2
  targets.append(objnum)

  # Save name description for datapoint.
  sceneName = line.split(",")[0].split("/")[-1]
  modelName = line.split(",")[-1].split("/")[-1].split(".")[0]
  trainNames.append(sceneName + ", " + modelName)


target_names = ["rectangular", "cylindrical", "irregular"]


# Load the actual data.
f = open("trainingfile.csv")
tData = []
for line in f:
  lsplit = line.split(",")
  datapoint = []
  for feature in lsplit:
    datapoint.append(float(feature))

  tData.append(datapoint)
data = np.array(tData) 

# Transform it into 2D with PCA.
y = np.array(targets)
X = np.delete(data, data.shape[1] - 1, 1) # Strip class.
pipeline = Pipeline([('scaling', StandardScaler()), ('pca', PCA(n_components=2))])
X_reduced = pipeline.fit_transform(data)


# Create plot.
trainNames = np.array(trainNames)
tmpTrainNames = np.array([])
fig = plt.figure()
for c, i, target_name in zip("rgb", [0, 1, 2], target_names):
  plt.scatter(X_reduced[y == i, 0], X_reduced[y == i, 1], c=c, label=target_name, picker=True)

  # Here i try to rearrange the order of the additonal information int he order the points
  # were plotted.
  tmpTrainNames = np.append(tmpTrainNames, trainNames[y == i])

trainNames = tmpTrainNames

plt.legend()
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
fig.canvas.mpl_connect('pick_event', onPick)
plt.show()

如果它太复杂,我可以尝试简化。告诉我。

1 个答案:

答案 0 :(得分:0)

由于我无法找到索引编制问题的解决方案,因此我以一种不同的,有点黑客的方式解决了这个问题。我没有指定类{0, 1, 2},而是使用zip()进行映射,而是直接将颜色值指定为类,并将整个类目标作为颜色参数。通过这个我可以一次绘制所有内容并保持数据点的原始顺序。

# y is here the class target with color values, e.g. ['r', 'g',..., 'r']
plt.scatter(X_reduced[:,0], X_reduced[:,1], c=y, picker=True)