Python:Matplotlib:matplotlib 中的垂直对齐图

The*_*ist 4 python plot matplotlib figure subplot

我想从多个来源读取数据并将它们绘制在彼此之上。我需要绘制它们的方式是x-axis在底部有一个标签,而其他的都应该与相同的 对齐x-axis,无论有哪些点可用。

以下是问题的示例:

import matplotlib.pylab as plt
import random
import matplotlib.gridspec as gridspec

random.seed(20)

#create x-axis of my data
x1 = range(0,10) #different range than the next one
x2 = range(1,9)

#create data (just random data corresponding the x1,x2)
data1 = [random.random() for i in x1]
data2 = [random.random()*1000 for i in x2]

gs = gridspec.GridSpec(2,1)
fig = plt.figure()

#first plot
ax = fig.add_subplot(gs[0])
ax.plot(x1,data1)
ax.set_ylabel(r'Label One', size =16)
ax.get_yaxis().set_label_coords(-0.1,0.5)
plt.tick_params(
    axis='x',          # changes apply to the x-axis
    labelbottom='off') # labels along the bottom edge are off

#second plot
ax = fig.add_subplot(gs[1])
ax.plot(x2,data2)
ax.set_ylabel(r'Label Two', size =16)
ax.get_yaxis().set_label_coords(-0.1,0.5)

plt.show()
Run Code Online (Sandbox Code Playgroud)

这产生了图: 在此处输入图片说明

请注意,上图x-axis与下图不匹配x-axis

我需要所有的图相互匹配,并将较小的图中没有数据的区域留空。这能实现吗?

如果您需要任何其他信息,请询问。

Diz*_*ahi 7

使用sharex参数add_subplot()

import matplotlib.pylab as plt
import random
import matplotlib.gridspec as gridspec

random.seed(20)

#create x-axis of my data
x1 = range(0,10) #different range than the next one
x2 = range(1,9)

#create data (just random data corresponding the x1,x2)
data1 = [random.random() for i in x1]
data2 = [random.random()*1000 for i in x2]

gs = gridspec.GridSpec(2,1)
fig = plt.figure()

#first plot
ax = fig.add_subplot(gs[0])
ax.plot(x1,data1)
ax.set_ylabel(r'Label One', size =16)
ax.get_yaxis().set_label_coords(-0.1,0.5)
plt.tick_params(
    axis='x',          # changes apply to the x-axis
    labelbottom='off') # labels along the bottom edge are off

#second plot
ax = fig.add_subplot(gs[1], sharex=ax)
ax.plot(x2,data2)
ax.set_ylabel(r'Label Two', size =16)
ax.get_yaxis().set_label_coords(-0.1,0.5)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明