Skip to main content
 首页 » 编程设计

python之重置 matplotlib 子图中的默认轴刻度

2025年05月04日10mate10pro

我想使用相同的 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 )

请您参考如下方法:

我认为这可以满足您的需求,但我认为它可能像您担心的那样“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()