54

matplotlib / pylab画像に含まれるプロットに適切にフィットするように図のサイズを自動的に変更する方法はありますか?

使用するデータに応じてアスペクト比が異なるヒートマップ(サブ)プロットを作成しています。

アスペクト比を計算して手動で設定できることに気づきましたが、もっと簡単な方法は確かにありますか?

4

6 に答える 6

69

Use bbox_inches='tight'

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)

...only works when saving images though, not showing them.

于 2009-08-14T15:57:48.907 に答える
19

Another way of doing this is using the matplotlib tight_layout function

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()
于 2016-12-26T15:38:47.263 に答える
18

just use aspect='auto' when you call imshow

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

it works even if it is just for showing and not saving

于 2012-05-04T11:51:06.687 に答える
5

you can try using 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()
于 2018-11-14T21:19:49.947 に答える
4

Do you mean changing the size of the image or the area that is visable within a plot?

The size of a figure can be set with Figure.set_figsize_inches. Also the SciPy Cookbook has an entry on changing image size which contains a section about multiple images per figure.

Also take a look at this question.

于 2009-08-13T10:31:09.633 に答える
1

Also possible to use ax.autoscale with ax object

ax.autoscale(enable=True) 
于 2019-01-30T02:35:07.457 に答える