0

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:

enter image description here

However, the SVG and PDF output look like this (apparently, the gradient is not confined to the path):

enter image description here

How can I make the SVG/PDF output look like the PNG output?

Stücke
  • 868
  • 3
  • 14
  • 41

1 Answers1

2

You will need to set the "image.composite_image" parameter to False when having multiple images with a different clip path in the same figure.

So add

plt.rcParams["image.composite_image"] = False

on top of your script.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • You are the real MVP! Thank for all your time. I hope you still get some of your research done! – Stücke Jul 12 '19 at 14:18