2015-09-02 51 views
2

有没有什么办法让我在一个matplotlib PathPatch上有多种颜色?我有以下代码,例如,我想给每个“段”自己的颜色(即从0,0到0,1的段可以是红色,从0,1到2,2可以是橙色,从4,3至5,3可以是黄色的)。我想做到这一点,而不使用集合,只是使用PathPatch多种颜色的一个PathPatch

import matplotlib as mpl 
import matplotlib.pyplot as plt 

fig2, ax2 = plt.subplots() 


verts = [(0,0), (0,1), (2,2), (4,3), (5,3)] 
codes = [1,2,2,1,2] 

pat = mpl.patches.PathPatch(mpl.patches.Path(verts, codes), fill=False, linewidth=2, edgecolor="red") 
ax2.add_patch(pat) 
ax2.set_xlim(-2, 6) 
ax2.set_ylim(-2, 6) 
+0

如果您只有strait部分,'LineCollection'也可能有帮助。 – tacaswell

回答

4

我还没有发现分配一个单独的颜色为mpl.patches.Path的段的方式 - 从the documentation,这并不似乎是可能(Path不采取与它的颜色/线宽任何参数的/ etc。)


但是 - 正如你在你的问题状态 - 可以使用a PathCollection不同颜色个别PathPatches结合起来。
重要的论据是match_original=True
对于其他类似的情况,这里有一个例子:

import matplotlib as mpl 
import matplotlib.pyplot as plt 

fig2, ax2 = plt.subplots() 


verts = [(0,0), (0,1), (2,2), (4,3), (5,3)] 
codes = [[1,2],[1,2],[1,1],[1,2],[1,2]] 

colors = ['red', 'orange', 'black', 'yellow'] 

pat = [mpl.patches.PathPatch(mpl.patches.Path(verts[i:i+2], codes[i]), fill=False, \ 
         linewidth=2, edgecolor=colors[i]) for i in range(len(verts)-1)] 

collection = mpl.collections.PatchCollection(pat, match_original=True) 
ax2.add_collection(collection) 

ax2.set_xlim(-2, 6) 
ax2.set_ylim(-2, 6) 

plt.show() 

注意事项:

  • codes现在变成了一个列表的列表,以确定每个部分单独
  • colors是一个列表带有颜色标识符的字符串。如果你想利用颜色表,看看this answer
  • 个别修补软件都存储在一个列表,pat,该循环代替完成
  • 所有pat补丁使用collections.PatchCollection组装 - 在这里,的重要参数是match_original=True,否则所有线路将是默认黑具有默认线宽

上面的例子产生这样的输出:

example