I have a list of 150 variables that have the following possible values:
domain = ['val1', 'val2', 'val2']
I want to convert these to be used as color for a matplot scatter plot. Currently I wrote a function to manually map from my data domain to a color range, something like:
colors = ['aquamarine','purple','blue']
color_map = dict(zip(domain, colors))
colorize = lambda x : color_map[x]
c = list(map(colorize, labels))
#and then I explicitly pass the array to scatter:
scatter = ax.scatter(t_x,
t_y,
c=c,
alpha=0.3,
cmap=plt.cm.cool,
s = 500)
This works, however, I must specify the color individual colors that each element of my domain gets mapped to. Is there a way to have matplotlib to this for me, so I can take advantage of cmaps? D3 has a way of mapping from a data domain to color range.
cla() Function. The cla() function in pyplot module of matplotlib library is used to clear the current axes. Syntax: matplotlib.pyplot.cla()
show() and plt. draw() are unnecessary and / or blocking in one way or the other.
This is an adapted version of @C_Z_'s answer, made to be more readily usable for plotting:
# x, y, and category_values should all be the same length (the # of data points)
import matplotlib.pyplot as plt
from matplotlib.cm import viridis
num_categories = len(set(category_values))
colors = [viridis(float(i)/num_categories) for i in category_values]
plt.scatter(x, y, color=colors)
You can import a colormap from matplotlib.cm
, then select individual colors from it by calling it as a function. It accepts input numbers from 0 to 1 (or from 1 to 255, it's a little weird) and gives you a color along the colormap.
import matplotlib
from matplotlib.cm import cool
def get_n_colors(n):
return[ cool(float(i)/n) for i in range(n) ]
Then you can generate colors for your categorical variable:
colors = get_n_colors(len(domain))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With