我想使用相同的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
设置?
(有些documentation)
答案 0 :(得分:1)
我认为这可以做你想要的,但我认为它可能像你担心的那样“hacky”。我也认为这可能是正确的方式。 :)
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()