Reputation: 7796
Is there any way for me to have multiple colors on one matplotlib PathPatch? I have the following code and I want to, for instance, give each "segment" its own color (i.e. the segment from 0,0 to 0,1 can be red, from 0,1 to 2, 2 can be orange, from 4,3 to 5,3 can be yellow). I would like to do this without using Collections and just using the 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)
Upvotes: 2
Views: 509
Reputation: 7905
I haven't found a way of assigning an individual color to the segments of a mpl.patches.Path
- and from the documentation, that does not appear to be possible (Path
does not take any arguments related to its color/linewidth/etc.)
However - and as you state in your question - one can use a PathCollection
to combine individual PathPatches
of different colors.
The important argument is match_original=True
.
For others in a similar situation, here is an example:
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()
Things to note:
codes
now became a list of lists to identify each section individually colors
is a list of strings with color identifiers. If you want to utilize a colormap, have a look at this answer pat
, the looping is done in place pat
are assembled using collections.PatchCollection
- here, the important argument is match_original=True
, otherwise all lines will be the default black with a default line thickness The above example produces this output:
Upvotes: 4