1

I drew a path on a plot with matplotlib and I would like to fill the shape with a gradient.

enter image description here

I came across this example:

Z, Z2 = np.meshgrid(np.linspace(0,1), np.linspace(0,1))
im = plt.imshow(Z-Z2, interpolation='bilinear', cmap=plt.cm.RdYlGn,
                origin='lower', extent=[0, 1, 0, 1],
                clip_path=patch, clip_on=True)
im.set_clip_path(patch)

  [1]: https://stackoverflow.com/questions/42063542/mathplotlib-draw-triangle-with-gradient-fill

I copy and pasted the piece of code which I deemed relevant into my code:

import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
import numpy as np

verts = [
    (200, 10), # 
    (125,110), # Control Point - half way c
    (50,110), # Control Point
    (50,110), # 
    (50,120), #
    (25,100), # 
    (50,80),  # 
    (50,90),  #
    (50,90),  # Control Point
    (125,90), # Controil Point half way x
    (200,10), # 
    (0., 0.), # 
    ]

codes = [Path.MOVETO,
         Path.CURVE4,
         Path.CURVE4,
         Path.CURVE4,
         Path.LINETO,
         Path.LINETO,
         Path.LINETO,
         Path.LINETO,
         Path.CURVE4,
         Path.CURVE4,
         Path.CURVE4,
         Path.CLOSEPOLY,
         ]

path = Path(verts, codes)

fig = plt.figure()
ax = fig.add_subplot(111)
patch = patches.PathPatch(path, facecolor='orange', lw=0, alpha=0.5)
ax.add_patch(patch)

Z, Z2 = np.meshgrid(np.linspace(0,1), np.linspace(0,1))
im = plt.imshow(Z-Z2, interpolation='bilinear', cmap=plt.cm.RdYlGn,
                origin='lower', extent=[0, 1, 0, 1],
                clip_path=patch, clip_on=True)
im.set_clip_path(patch)

ax.set_xlim(-0,225)
ax.set_ylim(-0,125)

plt.show()

However, the arrow remains orange.

How can I fill the arrow on my plot with a gradient from color 1 to color 2 (e.g. red to blue)?

Community
  • 1
  • 1
Stücke
  • 868
  • 3
  • 14
  • 41
  • 1
    Ähh, if you take the extent from 0 to 1, but your data limits from 0 to 225, the image will just be less than a percent of the axes size and hence not where your path is. – ImportanceOfBeingErnest Jul 04 '19 at 15:29
  • 1
    I think the linked example is still clear enough; of course one needs to adapt all the coordinates when the path is chosen differently. – ImportanceOfBeingErnest Jul 04 '19 at 15:36
  • Oh, fantastic, that already helps a lot :) – Stücke Jul 05 '19 at 07:41
  • However, when I save the picture in SVG I only see large boxes which i suppose delineate the boxes which I draw with the values in 'extent'. – Stücke Jul 05 '19 at 08:47
  • 1
    There should in general not be any problem saving the picture as svg. But feel free to update the question with the exact code you run, a screenshot of the image you get and the information needed like system and matplotlib versions, what kind of svg viewer you use etc. – ImportanceOfBeingErnest Jul 05 '19 at 09:20

0 Answers0