I am filling a path with a gradient based on an example which I have found here on Stackoverflow.
The code I came up with is as follows:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from matplotlib.colors import LinearSegmentedColormap
csmap = LinearSegmentedColormap.from_list('mycmap', ['blue', 'yellow', 'green'])
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
# 1
path = Path([[0,0],[0,1],[1,0],[0,0]])
patch = PathPatch(path, facecolor='none')
ax.add_patch(patch)
Z, Z2 = np.meshgrid(np.linspace(0,1), np.linspace(0,1))
im = plt.imshow(Z-Z2, interpolation='bilinear', cmap=csmap,
origin='lower', extent=[0.1, 0.9, 0.1, 0.7], # Distance Left,Right,bottom,top
clip_path=patch, clip_on=True)
im.set_clip_path(patch)
#2
path = Path([[1,1],[1,2],[2,1],[1,1]])
patch = PathPatch(path, facecolor='none')
ax.add_patch(patch)
Z, Z2 = np.meshgrid(np.linspace(0,1), np.linspace(0,1))
im = plt.imshow(Z-Z2, interpolation='bilinear', cmap=csmap,
origin='lower', extent=[1, 2, 1, 2], #X,Y & Y,X
clip_path=patch, clip_on=True)
im.set_clip_path(patch)
ax.set_xlim((0,3))
ax.set_ylim((0,3))
# Save plot
plt.savefig("output.svg", figsize=(24,12))
plt.savefig("output.png", figsize=(24,12))
plt.savefig("output.pdf", figsize=(24,12))
plt.show()
Everything workd out fine for the PNG output which is as follows:
However, the SVG and PDF output look like this (apparently, the gradient is not confined to the path):
How can I make the SVG/PDF output look like the PNG output?