2015-08-04 3 views
1

Я хотел бы читать данные из нескольких источников и строить их друг над другом. Мне нужно, чтобы они были построены с помощью одного x-axis, помеченного внизу, а остальные должны быть выровнены с тем же x-axis, независимо от того, какие точки доступны.Python: Matplotlib: Вертикально выровненные графики в matplotlib

Ниже приведен пример задачи:

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-axis-й не совпадает с нижним графиком по x-axis.

Мне нужно, чтобы все графики соответствовали друг другу, и оставляйте области без данных на небольших участках пустыми. Может ли это быть достигнуто?

Если вам нужна дополнительная информация, пожалуйста, спросите.

ответ

2

использовать 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

Смежные вопросы