2016-05-04 23 views
0

我想在pdf文檔中包含填充輪廓圖(例如TeX文檔)。 目前我使用pyplot s contourf,並保存到pdfpyplot s savefig。與此相關的問題是,與高分辨率png相比,地塊的大小變得相當大。減小矢量化輪廓圖的大小

減小尺寸的一種方法當然是減少圖中的水平數量,但太少的水平會產生不良的圖。我正在尋找一種簡單的方法,例如讓繪圖的顏色保存爲png,並將軸,刻度等等保存爲矢量化。

+0

我們可以看到一個典型的情節?你玩過nchunk參數嗎? –

+0

@tom給出的例子給出了一個典型的情節。我沒有玩nchunck參數,但爲了我的目的,選擇的答案是足夠的。最好的 –

回答

5

您可以使用Axes選項set_rasterization_zorder來執行此操作。

任何與zorder相比,您設置的任何東西都將被保存爲光柵化圖形,即使保存爲像pdf這樣的矢量格式。

例如:

import matplotlib.pyplot as plt 
import numpy as np 

data = np.random.rand(500,500) 

# fig1 will save the contourf as a vector 
fig1,ax1 = plt.subplots(1) 
ax1.contourf(data) 
fig1.savefig('vector.pdf') 

# fig2 will save the contourf as a raster 
fig2,ax2 = plt.subplots(1) 
ax2.contourf(data,zorder=-20) 
ax2.set_rasterization_zorder(-10) 
fig2.savefig('raster.pdf') 

# Show the difference in file size. "os.stat().st_size" gives the file size in bytes. 
print os.stat('vector.pdf').st_size 
# 15998481 
print os.stat('raster.pdf').st_size 
# 1186334 

你可以看到this matplotlib example更多的背景資料。


正如指出的@tcaswell,以rasterise只是一個藝術家,而不必影響其zorder,您可以使用.set_rasterized。但是,這似乎不適用於contourf,因此您需要遍歷由contourfset_rasterized創建的PathCollections。像這樣:

contours = ax.contourf(data) 
for pathcoll in contours.collections: 
    pathcoll.set_rasterized(True) 
+0

很好的答案,謝謝:D。對於那些想知道的人:首先繪製具有較低'zorder'的藝術家,並且具有比'set_rasterization_zorder'中給出的值低的值的藝術家將被光柵化。 –

+0

您也可以使用藝術家的'set_rasterized'來獨立於zorder對其進行光柵化。 – tacaswell

+1

@tcaswell:是的,但並非所有藝術家都有這種選擇。 'contourf'返回'matplotlib.contour.QuadContourSet'實例,它沒有'set_rasterized'選項。你可以遍歷它在'ax.collections'中創建的'PathCollections',並在它們每個上使用'set_rasterized',但我發現使用'set_rasterization_zorder'往往是一個更簡單的選項 – tom