2

我想使用相同的 x 轴在单个列中创建任意数量的图。

这是一个例子:

import numpy as np
from matplotlib import pyplot as plt

N=1000
x = np.linspace(-.5,1.5,num=N)
xshift = x-0.5
Bz = 30*np.exp(-xshift**8/0.00125)*np.sin(xshift*2.*np.pi)
Np = 30*np.exp(-xshift**10/0.00125)+5
Vx = 200*np.exp(-xshift**10/0.00125)+400

fig = plt.figure()

#list of tuples of the form `(data, label)`    
data_list = [(Bz,"B_z"),(Vx,"V_x"),(Np,"N_p")]

for i,(data,lab) in enumerate(data_list,1):
    ax = fig.add_subplot(len(data_list),1,i)
    ax.set_ylabel("$\mathrm{%s}$"%lab)
    ax.get_xaxis().set_ticklabels([])
    ax.plot(x,data)
else:
    #Reset default tick labels here on ax
    pass

plt.show()

对于这个图,最后一个图显示 xtic 标签是合乎逻辑的,而所有其他图都保留了该信息。我可以弹出最后一项data_list并明确地拼写出来,但这对我来说似乎很老套。有没有一种优雅的方法来告诉 matplotlib Axes 它应该恢复默认xticlabel设置?

(一些文件

4

1 回答 1

1

我认为这可以满足您的要求,但我认为它可能像您担心的那样“骇人听闻”。我也认为这可能是正确的方式。:)

import numpy as np
from matplotlib import pyplot as plt

N=1000
x = np.linspace(-.5,1.5,num=N)
xshift = x-0.5
Bz = 30*np.exp(-xshift**8/0.00125)*np.sin(xshift*2.*np.pi)
Np = 30*np.exp(-xshift**10/0.00125)+5
Vx = 200*np.exp(-xshift**10/0.00125)+400

fig = plt.figure()

#list of tuples of the form `(data, label)`    
data_list = [(Bz,"B_z"),(Vx,"V_x"),(Np,"N_p")]

left = .15
height = .2
width = .7
bottom = .0
axes_ticks = []
axes = []
for i,(data,lab) in enumerate(data_list,1):
    ax = fig.add_subplot(len(data_list),1,i)
    bottom += height
    ax.set_position((left, bottom, width, height))

    ax.set_ylabel("$\mathrm{%s}$"%lab)
    axes_ticks.append(ax.get_xaxis().get_ticklocs())
    ax.get_xaxis().set_ticks([])
    ax.plot(x,data)
    axes.append(ax)
else:
    #Reset default tick labels here on ax
    axes[0].get_xaxis().set_ticks(axes_ticks[0])


plt.show()
于 2012-11-08T16:24:02.890 回答