Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

python - Rasterizing multiple elements in matplotlib

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...