简体   繁体   English

在 matplotlib 中自动调整图形大小

[英]Resize a figure automatically in matplotlib

Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image?有没有办法自动调整图形大小以正确适合 matplotlib/pylab 图像中包含的图?

I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used.我正在根据所使用的数据创建纵横比不同的热图(子)图。

I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way?我意识到我可以计算纵横比并手动设置它,但肯定有更简单的方法吗?

Use bbox_inches='tight'使用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. ...只在保存图像时有效,而不是显示它们。

just use aspect='auto' when you call imshow调用 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')

it works even if it is just for showing and not saving即使它只是为了显示而不是保存,它也能工作

Another way of doing this is using the matplotlib tight_layout function另一种方法是使用 matplotlib tiny_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()

you can try using axis('scaled')你可以尝试使用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()

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 .可以使用Figure.set_figsize_inches设置图形的大小。 Also the SciPy Cookbook has an entry on changing image size which contains a section about multiple images per figure.此外, SciPy Cookbook有一个关于更改图像大小的条目,其中包含有关每个图形多个图像的部分。

Also take a look at this question .也看看这个问题

也可以将ax.autoscale与 ax 对象一起使用

ax.autoscale(enable=True) 

This is an old thread, but ProPlot introduces this feature. 这是一个旧线程,但是ProPlot引入了此功能。 Figure dimensions are optionally flexible , and the spacing between adjacent subplots and the figure edge are adjusted automatically to make room for content without messing up axes aspect ratios / adding unnecessary space. 图形尺寸可选地是灵活的 ,并且相邻子图与图形边缘之间的间距会自动调整,以为内容留出空间,而不会弄乱轴的长宽比/增加不必要的空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM