13

I'm having problems when rasterizing many lines in a plot using the rasterized=True keyword using the pdf output. Some version info:

  • matplotlib version 1.1.1rc
  • ubuntu 12.04
  • python 2.7.3

Here's a basic example that demonstrates my problem:

# Import matplotlib to create a pdf document
import matplotlib
matplotlib.use('Agg')
from matplotlib.backends.backend_pdf import PdfPages
pdf = PdfPages('rasterized_test.pdf')

import matplotlib.pylab as plt

# some test data
import numpy as np
ts = np.linspace(0,2*np.pi,100) * np.ones((200,100)) 
ts += (np.linspace(0, np.pi, 200)[np.newaxis] * np.ones((100,200))).T
ys = np.sin(ts)

fig = plt.figure() 
ax = fig.add_subplot(111)
ax.plot(ts[0], ys.T, color='r', lw=0.5, alpha=0.5, rasterized=True)
pdf.savefig()

pdf.close()

Essentially, I have a lot (200 in this case) of closely overlapping lines which makes the resulting figure (not rasterized) overly difficult to load. I would like to rasterize these lines, such that the axis labels (and other elements of the plot, not shown) remain vectors while the solution trajectories are flattened to a single raster background. However, using the code above, the image still takes a long time to load since each trajectory is independently rasterized, resulting in multiple layers. (If I open the resulting pdf with a program like inkscape, I can manipulate each trajectory independently.)

Is it possible to flatten all of the rasterized elements into a single layer, so the pdf size would be greatly reduced?

Thanks!

Zephyr
  • 11,891
  • 53
  • 45
  • 80
pstjohn
  • 521
  • 5
  • 13

1 Answers1

11

Change the code to:

ax = fig.add_subplot(111, rasterized=True)
ax.plot(ts[0], ys.T, color='r', lw=0.5, alpha=0.5)
HYRY
  • 94,853
  • 25
  • 187
  • 187
  • 7
    Thanks for the help! I wasn't aware that setting the rasterization in a different location would change the result. I ended up using a slightly different version, since I had other features on my plot I wanted to keep in vector formats. now I'm using for the desired effect: `ax = fig.add_subplot(111);` `ax.set_rasterization_zorder(1);` `ax.plot(ts[0], ys.T, color='r', lw=0.5, alpha=0.5, zorder=0)` – pstjohn Aug 24 '12 at 16:12
  • 1
    FYI: `set_rasterization_zorder(z)` means all artists of zorder below `z` would be rasterized. – Jongwook Choi Jul 28 '20 at 10:47
  • Your code rasterizes the whole figure (including e.g. axis/tick labels and legend) instead of the target elements, which is usually only the lines. – Shaun Han Jun 06 '22 at 15:11