一个PathPatch的多种颜色

时间:2015-09-02 17:10:04

标签: python matplotlib

有没有办法在一个matplotlib PathPatch上有多种颜色?我有以下代码,我想,例如,给每个"段"它自己的颜色(即从0,0到0,1的段可以是红色,从0到2,2可以是橙色,从4,3到5,3可以是黄色)。我想这样做而不使用Collections并只使用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)

1 个答案:

答案 0 :(得分:4)

我还没有找到一种方法可以为mpl.patches.Path的段和the documentation的段分配单独的颜色,这似乎是不可能的(Path不会任何与其颜色/线宽/等相关的参数。)

但是 - 正如您在问题中所述 - 可以使用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