在matplotlib中自动调整图形大小

puf*_*ish 35 python matplotlib

有没有办法自动调整图形大小以正确拟合matplotlib/pylab图像中包含的图?

我正在根据使用的数据创建长宽比不同的热图(子)图.

我意识到我可以计算宽高比并手动设置它,但肯定有一种更简单的方法吗?

puf*_*ish 45

使用bbox_inches ='紧'

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

X = 10*np.random.rand(5,3)

fig = plt.figure(figsize=(15,5),facecolor='w') 
ax = fig.add_subplot(111)
ax.imshow(X, cmap=cm.jet)

plt.savefig("image.png",bbox_inches='tight',dpi=100)
Run Code Online (Sandbox Code Playgroud)

...仅在保存图像时有效,而不显示图像.

  • Fig.add_subplot(111) 表示什么?我的意思是方括号内的数字 ((111)) (2认同)

Hom*_*ldo 15

只需在调用imshow时使用aspect ='auto'

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

X = 10*np.random.rand(5,3)
plt.imshow(X, aspect='auto')
Run Code Online (Sandbox Code Playgroud)

它即使只是为了显示而不是保存也能工作


Sim*_*bbs 10

另一种方法是使用matplotlib tight_layout函数

import matplotlib.pyplot as plt
fig,(ax) = plt.subplots(figsize=(8,4), ncols=1)
data = [0,1,2,3,4]
ax.plot(data)
fig.tight_layout()
fig.show()
Run Code Online (Sandbox Code Playgroud)


jel*_*015 5

你可以尝试使用axis('scaled')

import matplotlib.pyplot as plt
import numpy

#some dummy images
img1 = numpy.array([[.1,.2],[.3,.4]]) 
img2 = numpy.array([[.1,.2],[.3,.4]])

fig,ax = plt.subplots()
ax.imshow(img1,extent=[0,1,0,1])
ax.imshow(img2,extent=[2,3,0,1])
ax.axis('scaled') #this line fits your images to screen 
plt.show()
Run Code Online (Sandbox Code Playgroud)