我想在 matplotlib 图中有两个子图,它们的大小和位置相对于彼此,如下例所示(出于文体原因)。我见过的所有自定义子图位置和大小的示例仍然平铺并填充整个图形足迹。我该怎么做才能让最右边的情节定位在下面的一些空白处?
1410 次
2 回答
6
您需要想象一些放置子图的(虚拟)网格。
网格有 3 行 2 列。第一个子图涵盖所有三行和第一列。第二个子图仅覆盖第二列的第二行。行和列大小之间的比率不一定相等。
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()
此外,您仍然可以为hspace和wspace参数设置不同的值。
GridSpec 教程中给出了一个很好的概述。
因为在评论中提到:如果可能需要以英寸为单位的绝对定位,我建议直接添加所需尺寸的轴,
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()
于 2018-09-28T18:12:42.387 回答
1
--编辑:这个答案最终与@ImportanceOfBeingErnest 给出的答案惊人地相似,但采用了一种以英寸为单位而不是分数单位的布局控制方法。--
如果您gridspec使用 将其网格化,然后使用所需的比率或列的跨度填充网格,它会有所帮助。对于我制作的许多图形,我需要它们很好地适应页面,所以我经常使用这种模式来将网格控制到 10 英寸。
import matplotlib.pyplot as plt
from matplotlib import gridspec
fig = plt.figure(figsize=(7, 5)) # 7 inches wide, 5 inches tall
row = int(fig.get_figheight() * 10)
col = int(fig.get_figwidth() * 10)
gsfig = gridspec.GridSpec(
row, col,
left=0, right=1, bottom=0,
top=1, wspace=0, hspace=0)
gs1 = gsfig[:, 0:30]
# these spans are in tenths of an inch, so left-right
# spans from col 0 to column 30 (or 3 inches)
ax1 = fig.add_subplot(gs1)
gs1 = gsfig[20:40, 35:70] # again these spans are in tenths of an inch
ax1 = fig.add_subplot(gs1)
于 2018-09-28T18:28:18.463 回答



