如何在Matplotlib中完全自定义子图大小 [英] How to fully customize subplot size in matplotlib

查看:179
本文介绍了如何在Matplotlib中完全自定义子图大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在matplotlib图中有两个子图,如下图所示,它们的大小和位置相对于彼此(出于风格原因).我见过的用于自定义子图位置和大小的所有示例仍然平铺并填充整个图形足迹.我该怎么做才能让最右边的图定位有一些空格,如下所示?

I want to have two subplots in a matplotlib figure that are sized and positioned relative to each other like the example below (for stylistic reasons). All the examples I've seen for customizing subplot placement and sizes still tile and fill the entire figure footprint. What can I do to get the rightmost plot positioned with some whitespace like below?

推荐答案

您需要想象一些(虚拟)网格,子图放置在该网格上.

You need to imagine some (virtual) grid on which the subplots are placed.

网格具有3行2列.第一个子图覆盖所有三行和第一列.第二个子图仅覆盖第二列的第二行.行和列大小之间的比率不一定相等.

The grid has 3 rows and 2 columns. The first subplot covers all three rows and the first column. The second subplot covers only the second row of the second column. The ratios between the row and column sizes are not necessarily equal.

import matplotlib.pyplot as plt
import matplotlib.gridspec

gs = matplotlib.gridspec.GridSpec(3,2, width_ratios=[1,1.4], 
                                       height_ratios=[1,3,1])

fig = plt.figure()
ax1 = fig.add_subplot(gs[:,0])
ax2 = fig.add_subplot(gs[1,1])

plt.show()

此外,您仍然可以为 hspacewspace 参数设置不同的值.

In addition you may still set different values to hspace and wspace parameters.

GridSpec教程给出了很好的概述.

<小时>因为在评论中提到:如果可能需要以英寸为单位的绝对定位,我建议直接添加所需大小的轴,


Because it was mentionned in the comments: If absolute positionning in units of inches may be desired, I would recommend directly adding an axes in the desired size,

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
w,h = fig.get_size_inches()
div = np.array([w,h,w,h])

# define axes in by rectangle [left, bottom, width, height], numbers in inches
ax1 = fig.add_axes(np.array([.7, .7, 1.8, 3.4])/div)
ax2 = fig.add_axes(np.array([3, 1.4, 3, 2])/div)

plt.show()

这篇关于如何在Matplotlib中完全自定义子图大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆