gpt4 book ai didi

python - 一个 PathPatch 有多种颜色

转载 作者:行者123 更新时间:2023-11-28 22:41:41 24 4
gpt4 key购买 nike

有没有办法让我在一个 matplotlib PathPatch 上有多种颜色?我有以下代码,例如,我想给每个“段”赋予自己的颜色(即从 0,0 到 0,1 的段可以是红色,从 0,1 到 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)

最佳答案

我还没有找到一种方法来为 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

关于python - 一个 PathPatch 有多种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32359197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com