Can we apply specific colors to our clusters?


#1

Question

In the context of this exercise, we apply colors to the points by setting c=labels in the plt.scatter() method call. Can we apply specific colors to our clusters?

Answer

Yes, you can!

To specify colors for each cluster, you can assign a color to each point individually, depending on what their label was. We can do this by creating a new list, iterating over each data point’s label, and then adding the color to the list based on that label.

In the following example, we set colors, as string values, to each point based on their label, “red” for label 0, “blue” for label 1, and “green” for label 2.

# Create the empty list
colors = []

# Iterate over each label, and 
# assign the color based on the label
for label in labels:
  if label == 0:
    colors.append("red")
  elif label == 1:
    colors.append("blue")
  elif label == 2:
    colors.append("green")

# Plot the scatter plot using this list for the colors
plt.scatter(x, y, c=colors, alpha=0.5)