2012-10-22 411 views
9

我必須做出一個向量圖,我想只看到載體,而不軸,標題等所以這裏是我如何努力做到這一點:matplotlib savefig圖像尺寸與bbox_inches =「緊」

pyplot.figure(None, figsize=(10, 16), dpi=100) 
pyplot.quiver(data['x'], data['y'], data['u'], data['v'], 
       pivot='tail', 
       units='dots', 
       scale=0.2, 
       color='black') 

pyplot.autoscale(tight=True) 
pyplot.axis('off') 
ax = pyplot.gca() 
ax.xaxis.set_major_locator(pylab.NullLocator()) 
ax.yaxis.set_major_locator(pylab.NullLocator()) 
pyplot.savefig("test.png", 
       bbox_inches='tight', 
       transparent=True, 
       pad_inches=0) 

,儘管我努力在1600年前拍攝1000張照片,但我在1280年之前獲得了775張照片。如何使其達到所需的尺寸? 謝謝。

UPDATE所提出的解決方案的工作,除了在我的情況下,我也不得不手動設置軸限制。否則,matplotlib無法找出「緊」的邊界框。

+2

對於MPL,有兩個DPI值必須保持直線。您在創建「圖形」對象時指定的一個用於在屏幕上交互顯示圖形。另一個DPI值適用於保存的文件(以任何格式),在您調用savefig時指定。這就是爲什麼解決方案@unutbu發佈工作。 –

回答

12
import matplotlib.pyplot as plt 
import numpy as np 
sin, cos = np.sin, np.cos 

fig = plt.figure(frameon = False) 
fig.set_size_inches(5, 8) 
ax = plt.Axes(fig, [0., 0., 1., 1.],) 
ax.set_axis_off() 
fig.add_axes(ax) 

x = np.linspace(-4, 4, 20) 
y = np.linspace(-4, 4, 20) 
X, Y = np.meshgrid(x, y) 
deg = np.arctan(Y**3-3*Y-X) 
plt.quiver(X, Y, cos(deg), sin(deg), pivot = 'tail', units = 'dots', color = 'red',) 
plt.savefig('/tmp/test.png', dpi = 200) 

產生

enter image description here

您可以通過設置數字使產生的圖像1000x1600像素爲5×8英寸

fig.set_size_inches(5, 8) 

與DPI = 200節省:

plt.savefig('/tmp/test.png', dpi = 200) 

刪除邊框的代碼取自here

(上面張貼的圖片沒有按比例,因爲1000x1600比較大)。