1

I'm using some sample code I got from: https://stackoverflow.com/a/29331211/9469766

I'm attempting to save as pdf but whenever I do the gradient colors are formatted incorrectly. But if I simply show instead of saving or save the file as .png instead, the gradients appear correctly. Which leads me to believe that its the .pdf format that's the issue. Are there specific parameters that I need to set when saving as pdf?

Expected Image Output: Expected Image Output

Actual Image Output Actual Image Output

My code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.patches import Polygon
np.random.seed(1977)
import os

def main():
    home_dir = os.path.expanduser('~/Desktop/test2.pdf')
    x, y = generate_data(100)
    for _ in range(5):
        gradient_fill(*generate_data(100))
    # plt.show()
    plt.savefig(home_dir, rasterized = True, dpi=300)
    plt.close()

def generate_data(num):
    x = np.linspace(0, 100, num)
    y = np.random.normal(0, 1, num).cumsum()
    return x, y

def gradient_fill(x, y, fill_color=None, ax=None, **kwargs):
    """
    """
    if ax is None:
        ax = plt.gca()

    line, = ax.plot(x, y, **kwargs)
    if fill_color is None:
        fill_color = line.get_color()

    zorder = line.get_zorder()
    alpha = line.get_alpha()
    alpha = 1.0 if alpha is None else alpha

    z = np.empty((100, 1, 4), dtype=float)
    rgb = mcolors.colorConverter.to_rgb(fill_color)
    z[:,:,:3] = rgb
    z[:,:,-1] = np.linspace(0, alpha, 100)[:,None]

    xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()
    im = ax.imshow(z, aspect='auto', extent=[xmin, xmax, ymin, ymax],
                   origin='lower', zorder=zorder)

    xy = np.column_stack([x, y])
    xy = np.vstack([[xmin, ymin], xy, [xmax, ymin], [xmin, ymin]])
    clip_path = Polygon(xy, facecolor='none', edgecolor='none', closed=True)
    ax.add_patch(clip_path)
    im.set_clip_path(clip_path)

    ax.autoscale(True)
    return line, im

main()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712

1 Answers1

1

The problem is the same as in https://github.com/matplotlib/matplotlib/issues/7151.

The solution is to use the "image.composite_image" rc parameter and set it to False.

plt.rcParams["image.composite_image"] =False
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712