Matplotlib不同大小的子块

2024-04-25 15:18:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要给一个数字加上两个子块。一个子块需要大约是第二个子块的三倍宽(同样的高度)。我使用GridSpeccolspan参数完成了这项工作,但是我想使用figure来完成这项工作,以便可以保存到PDF格式。我可以使用构造器中的figsize参数调整第一个图,但如何更改第二个图的大小?


Tags: 参数高度pdf格式数字子块figurecolspan
3条回答

您可以使用^{}figure

import numpy as np
import matplotlib.pyplot as plt 
from matplotlib import gridspec

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
fig = plt.figure(figsize=(8, 6)) 
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1]) 
ax0 = plt.subplot(gs[0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[1])
ax1.plot(y, x)

plt.tight_layout()
plt.savefig('grid_figure.pdf')

resulting plot

另一种方法是使用subplots函数并使用gridspec_kw传递宽度比:

import numpy as np
import matplotlib.pyplot as plt 

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)

f.tight_layout()
f.savefig('grid_figure.pdf')

可能最简单的方法是使用subplot2grid,如Customizing Location of Subplot Using GridSpec所述。

ax = plt.subplot2grid((2, 2), (0, 0))

等于

import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])

所以bmu的例子变成:

import numpy as np
import matplotlib.pyplot as plt

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)

plt.tight_layout()
plt.savefig('grid_figure.pdf')

相关问题 更多 >

    热门问题