Skip to main content
 首页 » 编程设计

python之绘制两个不同颜色的列表

2025年02月15日10think

我用类似 Matlba 的 stem() 绘制了一个列表 (s_n_hat),如下所示:

markerline, stemlines, _ = plt.stem(s_n_hat, '-.') 
plt.setp(markerline, 'markerfacecolor', 'b') 
plt.setp(baseline, 'color','r', 'linewidth', 2) 
plt.show() 

在我的实际应用程序中,我想用蓝色绘制命中,用红色绘制未命中,我应该怎么做?所以,一些元素应该是蓝色的,一些是红色的。

假设我的向量的第一部分是命中,第二部分是未命中,我尝试这样做:

s_n_hat = [1, -1, 1, 1, -1, 1, 1, 1, 1] 
markerline1, stemlines, _ = plt.stem(s_n_hat[0:5], '-.') 
plt.setp(markerline1, 'markerfacecolor', 'b') 
markerline2, stemlines, _ = plt.stem(s_n_hat[6:9], '-.') 
plt.setp(markerline2, 'markerfacecolor', 'r') 
plt.setp(baseline, 'color','r', 'linewidth', 2) 
plt.show() 

我希望第一个元素是蓝色的,其他元素是红色的,但它们似乎是混合的:

有什么想法吗?

请您参考如下方法:

来自documentation :

If no * x * values are provided, the default is (0, 1, ..., len (y) -1)

然后需要传一个x,但是点重叠了。像这样的东西:

s_n_hat = [1, -1, 1, 1, -1, 1, 1, 1, 1] 
x1 = list(range(0, 5)) 
x2 = list(range(5, 8)) 
markerline1, stemlines, _ = plt.stem(x1, s_n_hat[0:5], '-.') 
plt.setp(markerline1, 'markerfacecolor', 'b') 
markerline2, stemlines, _ = plt.stem(x2, s_n_hat[6:9], '-.') 
plt.setp(markerline2, 'markerfacecolor', 'r') 
plt.show()