如何自动将matplotlib中所有子图的x轴比例设置为相等?

时间:2018-07-26 16:25:11

标签: python matplotlib

在此示例中:

import numpy as np
import matplotlib.pyplot as plt

t1 = np.linspace(0, 1, 1000)
t2 = np.linspace(0, 0.5, 1000)

plt.figure(figsize=(10,5))

plt.subplot(121)
plt.plot(t1, np.sin(t1 * np.pi))

plt.subplot(122)
plt.plot(t2, np.sin(t2 * np.pi))

plt.show()

enter image description here

如何压缩第二个图的大小,以使两个子图的x轴具有相同的比例尺?因此看起来像这样:

enter image description here

我正在寻找一种简单而自动的方法,因为我有30多个子图,并且希望它们都具有相同的x轴比例。

4 个答案:

答案 0 :(得分:1)

通过指定定义子图比例的gridspec_kw parameter,可以在两个x轴上近似相同的单位长度。

import numpy as np
from matplotlib import pyplot as plt

t1 = np.linspace(0, 1, 1000)
t2 = np.linspace(0, 0.5, 1000)

fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = {"width_ratios": [np.max(t1)-np.min(t1), np.max(t2)-np.min(t2)]})

ax1.plot(t1, np.sin(t1 * np.pi))
ax2.plot(t2, np.sin(t2 * np.pi))

plt.show()

样本输出:
enter image description here

答案 1 :(得分:0)

您可以使用plt.xlim(xmin, xmax)设置图的域。使用plt.xlim()而不给其参数将返回图形的当前xmin / xmaxplt.ylim()也是如此。

答案 2 :(得分:0)

一种大概不是很合适的方法,但我认为对{@ 3}}的使用会有用:

plt.subplot2grid((ROWS, COLS), (START_ROW, START_COL), rowspan=ROWSPAN, colspan=COLSPAN)

使用此方法,您可以创建两个子图,这些子图的总和为所需的长度,并相应地将colspan传递到x轴的长度,例如:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5)
y = np.linspace(0, 10)

plt.figure(figsize=(10,5)) # as specified from your code

# x.max() + y.max() is the total length of your x axis
# this can then be split in the parts of the length x.max() and y.max() 
# the parts then should have the correct aspect ratio
ax1 = plt.subplot2grid((1, int(x.max()+y.max()), (0, 0), colspan=int(x.max()))
ax2 = plt.subplot2grid((1, int(x.max()+y.max()), (0, int(x.max())), colspan=int(y.max()))

ax1.plot(x, np.sin(x))
ax2.plot(y, np.sin(y))
plt.show()

对我来说,比例似乎是相同的,如果还应该调整subplot2grid,您仍然需要调整xticklabels

答案 3 :(得分:0)

您可以通过更改纵横比来实现:

import numpy as np
import matplotlib.pyplot as plt

t1 = np.linspace(0, 1, 1000)
t2 = np.linspace(0, 0.5, 1000)

plt.figure(figsize=(10,5))

fig,ax = plt.subplots(nrows = 1,ncols = 2)

ax[0].plot(t1, np.sin(t1 * np.pi))

x1,x2 =ax[1].get_xlim()
x_diff = x2-x1
y1,y2 = ax[1].get_ylim()
y_diff = y2-y1

#plt.subplot(122)
ax[1].plot(t2, np.sin(t2 * np.pi))
ax[1].set_aspect(y_diff/x_diff)

输出: enter image description here

相关问题