Yoskutik
Yoskutik

Reputation: 2089

Matplotlib. How to use the same colors for plot each time?

I have this code:

import matplotlib.pyplot as plt

plt.figure(figsize=[13, 8])
for x in range(10):
    labels = pred_labels[:len(predict)]
    plt.scatter(tnse[:, 0][labels == x], tnse[:, 1][labels == x], label=x)
plt.legend(fontsize='large')
plt.title('MNIST predictions')
plt.show()

I have predict - the maxtrix which is neural network output and pred_label which is vector of numbers [0..9]

The code should plot something like that: scatter

And it does, but each group of dots has different color each time I want to plot them. Is there a way to make them have a constant color?

I tried to use this:

plt.scatter(tnse[:, 0][labels == x], tnse[:, 1][labels == x], label=x, c=x)

But it didn't work

Upvotes: 0

Views: 563

Answers (2)

incarnadine
incarnadine

Reputation: 700

You can use itertools to cycle over 10 colors (giving the same color to each class every time you run it). Just replace colors with your colors to cycle

import itertools

colors = itertools.cycle([colors])
plt.scatter(tnse[:, 0][labels == x], tnse[:, 1][labels == x], label=x, color=next(colors))

EDIT: According to comment below

Upvotes: 0

lavalade
lavalade

Reputation: 368

A solution that I often use :

  • create N colors from a colormap,
  • specify color to each plot.

Here is a minimal example inspired from yours :

import matplotlib.pyplot as pp
from numpy import random, linspace

# datas
x, y = [], []
for _ in range(10):
    x.append(random.rand() + .1 * random.rand(32))
    y.append(random.rand() + .1 * random.rand(32))

# colors
colors = pp.cm.plasma(linspace(0, 1, 10))

# plot
pp.close(0)
pp.figure(0)
for color, i in zip(colors, range(10)):
    pp.plot(x[i], y[i], 'o', label=f"{i}", mec=color, mfc=color)
pp.legend()
pp.show()

that outputs: enter image description here

Upvotes: 1

Related Questions