Home > OS >  Ploting a list of points with different color that is determined by another list?
Ploting a list of points with different color that is determined by another list?

Time:09-11

I'm sure this is quite simple but couldn't find any examples. I have a list of tuples (x,y) and I wish to print these in color according to another list of labels using matplotlib.

How can I do that? Thanks!

CodePudding user response:

The usual imports

import numpy as np
import matplotlib.pyplot as plt

faking some data

labels = 'a b c a b c a b c'.split()
tuples = [(1, 2), (3, 4), (5, 6), (3, 2), (2, 1), (1, 0), (5, 1), (3, 1), (4, 1)]

you need a way to map labels to colors, and a dictionary is a mapping, isn't it?

color = dict(zip(set(labels), 'red,blue,purple,green'.split(',')))

next, you can plot the individual points with their color, with just a difference, you specify a greater zorder so that they are at the front of the drawing

for (x, y), label in zip(tuples, labels):
    plt.scatter(x, y, color=color[label], zorder=2)

if you want to have a legend, because x and y are set at the end of the previous loop, using zorder you can plot the labelled dots behind the real data dot, this time specifying a label

for label in set(labels):
    plt.scatter(x, y, color=color[label], label=label, zorder=1)
plt.legend()

enter image description here

  • Related