在matplotlib中用不同的alpha绘制几行

时间:2019-11-18 14:18:00

标签: python matplotlib

我想从numpy矩阵形式以相同的颜色,但不同的alpha绘制多条线。我尝试通过rgba_colors指定它,因为这适用于散点图。但是,这是基于点的,而在这里我想每行使用它。我尝试过

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)

但是,这导致:

ValueError: Invalid RGBA argument

3 个答案:

答案 0 :(得分:2)

虽然matplotlib scatter函数既接受单一颜色也接受颜色列表作为参数,但plot函数仅接受单一颜色。您仍然可以使用简单的循环来获取所需的内容:

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

答案 1 :(得分:1)

使用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

答案 2 :(得分:0)

据此:https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html 您只能为一个plot()命令指定一种颜色。