简体   繁体   中英

Fast way to convert an array of integers to color strings or color values in python

I am trying to plot data points according to their class labels.

import numpy
import matplotlib as plt
x = numpy.random.uniform(size = [1, 15])
labels = numpy.array([1,2,2,2,2,1,1,2,3,1,3,3,1,1, 3])
plt.plot(x, 'o', c = labels)

When I did the above, Python complained that the color values need to be 0, 1. Then I used

plt.plot(x, 'o', c = labels/max(labels))

There is no error generated. A plot window pops up, but there is nothing in the plot window. I am wondering what is the correct way to define the colors that are according to the data labels?

I am also trying to color nodes according to the class labels. This is done in networkx. A simple example is:

import networkx as nx
G=nx.complete_graph(5)
nx.draw(G, node_col = node_labels)

The array node_labels will be the labels of the 5 vertices. I tried using the same approaches I tried above, but the network always has red nodes.

Any insight will be appreciated. Thanks!

Since your labels are integers you can use them as an index for a list of colors:

colors = ['#e41a1c', '#377eb8', '#4daf4a']

then, using scatter is simpler than plot since you can provide a list/sequence of colors:

labels = np.random.randint(low=0, high=3, size=20)
plt.scatter(np.random.rand(20), np.random.rand(20), color=np.array(colors)[labels])

Which will give you this:

在此处输入图片说明

To get nice colors you can use colorbrewer .

In order to do what you're seeking, your labels array must be a floating-point array. From the look of it, [labels] is being interpreted as a integer array. Thus, modify your code as follows to achieve the desired result.

plt.plot(x, 'o', c = labels)

should be changed to:

plt.plot(x, 'o', c = labels.astype(numpy.float) 

Stay awesome!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM