获取子图以填充图形

获取子图以填充图形

本文介绍了Matplotlib:获取子图以填充图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望获得一些建议,以了解在将图像绘制为子图时如何覆盖默认的matplotlib行为,从而使子图大小似乎与图形大小不匹配.我想设置我的图形大小(例如,匹配 A4 页面的宽度)并让子图自动拉伸以填充可用空间.在下面的例子中,下面的代码给出了一个面板之间有很多空白的图形:

I would please like suggestions for how to override the default matplotlib behaviour when plotting images as subplots, whereby the subplot sizes don't seem to match the figure size. I would like to set my figure size (e.g. to match the width of an A4 page) and have the subplots automatically stretch to fill the space available. In the following example, the code below gives a figure with a lot of white space between the panels:

import numpy as np
import matplotlib.pyplot as plt

data=np.random.rand(10,4)

#creating a wide figure with 2 subplots in 1 row
fig,ax=plt.subplots(1,2, figsize=(9,3))
ax=ax.reshape(1,len(ax))

for i in [0,1]:
    plt.sca(ax[0,i])
    plt.imshow(data,interpolation='nearest')
    plt.colorbar()

我希望将子图水平拉伸,以便它们填充图形空间.我将沿着每个轴制作许多具有不同数量值的类似图,并且图之间的空间似乎取决于 x 值与 y 值的比率,所以我想知道是否有一个很好的通用方法来设置子图的宽度以填充空间.可以以某种方式指定子图的物理大小吗?几个小时以来,我一直在寻找解决方案,因此在此先感谢您提供的任何帮助.

I would like the subplots to be stretched horizontally so that they fill the figure space. I will make many similar plots with different numbers of values along each axis, and the space between the plots appears to depend on the ratio of x values to y values, so I would please like to know if there is a good general way to set the subplot widths to fill the space. Can the physical size of subplots be specified somehow? I've been searching for solutions for a few hours, so thanks in advance for any help you can give.

推荐答案

首先,当您有 Axes 对象作为处置时,您正在使用对 plt 的调用.那条路通向痛苦.其次, imshow 将轴比例的高宽比设置为1.这就是轴如此窄的原因.知道所有这些,你的例子变成:

First, you're using calls to plt when you have Axes objects as your disposal. That road leads to pain. Second, imshow sets the aspect ratio of the axes scales to 1. That's why the axes are so narrow. Knowing all that, your example becomes:

import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(10,4)

#creating a wide figure with 2 subplots in 1 row
fig, axes = plt.subplots(1, 2, figsize=(9,3))

for ax in axes.flatten():  # flatten in case you have a second row at some point
    img = ax.imshow(data, interpolation='nearest')
    ax.set_aspect('auto')

plt.colorbar(img)

在我的系统上,它看起来像这样:

On my system, that looks like this:

这篇关于Matplotlib:获取子图以填充图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:55