Mike
Mike

Reputation: 4255

Plotting several lines with different alphas in matplotlib

I would like to draw several lines from a numpy matrix form with the same color, but different alphas. I tried to specify it via rgba_colors since this works for scatter plots. However, that is on a point basis, while here I would like to have it per line. I have tried

num_lines = 4
lines = np.outer(np.arange(1,num_lines+1), np.arange(1,10))    
alphas = np.linspace(0.1, 1, num_lines)
rgba_colors = np.zeros((num_lines, 4))
# for red the first column needs to be one
rgba_colors[:, 0] = 1.0
# the fourth column needs to be your alphas
rgba_colors[:, 3] = alphas
plt.plot(lines, color=rgba_colors)

However, that leads to:

ValueError: Invalid RGBA argument

Upvotes: 1

Views: 1414

Answers (3)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

Use a LineCollection:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

num_lines = 4
y = np.outer(np.arange(1,num_lines+1), np.arange(1,10))  
x = np.tile(np.arange(y.shape[1]), y.shape[0]).reshape(y.shape)

segs = np.stack((x, y), axis=2)

alphas = np.linspace(0.1, 1, num_lines)
rgba_colors = np.zeros((num_lines, 4))
# for red the first column needs to be one
rgba_colors[:, 0] = 1.0
# the fourth column needs to be your alphas
rgba_colors[:, 3] = alphas

lc = LineCollection(segs, colors=rgba_colors)
plt.gca().add_collection(lc)
plt.autoscale()
plt.show()

enter image description here

Upvotes: 2

lenik
lenik

Reputation: 23498

According to this: https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html you may specify only one color for one plot() command.

Upvotes: 1

Andrea
Andrea

Reputation: 3077

While the matplotlib scatter function accepts both a single color or a list of colors as an argument, the plot function only accepts a single one. You still can use a simple loop to obtain what you need:

num_lines = 4
lines = np.outer(np.arange(1,num_lines+1), np.arange(1,10))    
alphas = np.linspace(0.1, 1, num_lines)

rgba_colors[:, 3] = alphas
for line, alpha in zip(lines, alphas):
    plt.plot(line, color='red', alpha=alpha)

enter image description here

Upvotes: 2

Related Questions