2016-12-07 88 views
0

我似乎无法弄清楚如何根据一些简单的逻辑来改变matplotlib中的linecolor。基于逻辑改变matplotlib中的线颜色

举例来说,假设我有:

import numpy as np 
from matplotlib import pyplot as plt 

A = [1,2,3,4,5] 
B = [2,4,6,8,10] 
C = [1,3,5,6,7] 
D = [1,2,3,3,3] 
combined = [A,B,C,D] 

现在,让我们说,我想matplotlib绘制这是一个线图。因此,根据每个列表的组合,应该有4条单独的行。

我想添加条件,如果列表中的数字(组合)大于5,那么各条线是蓝色的。否则,让个别行变成橙色。

我该如何去做这样的事情?我知道以下内容会将其绘制得很好。

np_combined = np.array(combined) 
times = np.linspace(0,1,5) 
plt.plot(times,np_combined.T) 

我需要双循环吗?我尝试了不止几次,但似乎每次都会收到错误。

for h in np_combined: 
    for k in range(5): 
     if k > 5: 
      plt.plot(times,k,color = 'blue') 
     else: 
      plt.plot(times,k,color = 'orange') 

错误是EOL同时根据您尝试扫描字符串字面

+0

你试过什么类型的错误? – rassar

+0

编辑我的尝试 – DudeWah

回答

1

,尝试:

for sublist in np_combined: 
    if max(sublist) > 5: 
     plt.plot(times,sublist,color = 'blue') 
    else: 
     plt.plot(times,sublist,color = 'orange') 

此外,由于你的错误是你缺少一个结束引号(这就是EOL手段),错误可能在另一行。

+0

这太棒了。我很伤心,我没有使用max。解决了它。 它应该是:plt.plot(times,sublist,color ='b') – DudeWah

+0

@DudeWah你是对的,答案已更新。 – rassar

2

rassar's answer,使用条件选择颜色(或绘制样式)是否正确。对于简单的情况,这非常好。

对于更复杂的情况,只要为他们设置自己,还有另一种选择:决策功能。您通常在d3jsBokeh和可视化应用程序中看到这些内容。

对于一个简单的例子,它是这样的:

color_choice = lambda x: 'blue' if x > 5 else 'orange' 

for sublist in np_combined: 
    plt.plot(times, sublist, color=color_choice(max(sublist))) 

这里color_choice也可以是一个传统的函数定义。使用lambda函数仅仅是因为它是一个简短的单线程。

对于简单的情况,定义一个选择函数可能不会比条件更好。但是说你也想定义一个线条样式,而不是使用与颜色选择相同的条件。例如: -

for sublist in np_combined: 
    largest = max(sublist) 
    if largest > 5: 
     if largest > 10: 
      plt.plot(times, sublist, color='blue', ls='--') 
     else: 
      plt.plot(times, sublist, color='blue', ls='-') 
    else: 
     if largest <= 2: 
      plt.plot(times, sublist, color='orange', ls='.') 
     else: 
      plt.plot(times, sublist, color='orange', ls='-') 

现在你在一个混乱的泡菜,因为你只是相对简单的颜色和线条的选择这么多的代码。这是重复性的,违反了软件工程原理,引发错误。

决策功能,可以极大地清理一下:

color_choice = lambda x: 'blue' if x > 5 else 'orange' 

def line_choice(x): 
    if x > 10: return '--' 
    if x > 2: return '-' 
    return '.' 

for sublist in np_combined: 
    largest = max(sublist) 
    plt.plot(times, sublist, 
      color=color_choice(largest)), 
      ls=line_choice(largest)) 

这不仅清理了代码,本地化决策逻辑,它可以更容易地改变你的颜色,样式,和其他选择,因为你的程序演变。美中不足的是Python缺乏AFIAK,D3的excellent selection of mapping functions, aka "scales"

+0

这是如此翔实,真的会在未来帮助我。非常感谢你花时间写出所有明确的内容。 – DudeWah