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

5
我希望能够从多个数据源读取数据并将它们绘制在彼此之上。我需要它们的绘图方式是有一个单独的 x 轴标签位于底部,其他的应该与相同的 x 轴对齐,无论有哪些点可用。
以下是问题的示例:
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()

这将产生以下图形:enter image description here 请注意,上部图的`x轴`与下部图的`x轴`不匹配。
我需要所有的图都彼此匹配,并在较小的图中保留没有数据的区域为空。这可以实现吗?
如果您需要任何其他信息,请提出要求。
1个回答

10

使用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()

enter image description here


请问您为什么更喜欢使用 gridspec.GridSpec 而不是 fig.add_subplot(211)?谢谢! - Boson Bear

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接