在matplotlib中栅格化多个元素 [英] Rasterizing multiple elements in matplotlib

查看:87
本文介绍了在matplotlib中栅格化多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用pdf输出使用rasterized = True关键字对图中的多条线进行栅格化时,我遇到了问题. 一些版本信息:

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

  • matplotlib版本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()

从本质上讲,我有很多(在这种情况下为200)紧密重叠的线,这使得生成的图形(未栅格化)非常难以加载.我想对这些线进行栅格化,以使轴标签(以及图中的其他元素,未显示)仍然是矢量,而求解轨迹被展平为单个栅格背景.但是,使用上面的代码,由于每个轨迹都被独立光栅化,从而导致多层,因此图像加载仍然需要花费很长时间. (如果我使用inkscape之类的程序打开生成的pdf,则可以独立地操纵每个轨迹.)

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.)

是否可以将所有栅格化的元素展平为单层,从而大大减小pdf的大小?

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

谢谢!

推荐答案

将代码更改为:

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

这篇关于在matplotlib中栅格化多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆