Skip to main content
 首页 » 编程设计

python之如何设置双x轴标签

2025年05月04日17bhlsheji

我在这里:

my figure for now

然后我想改成这样:

double x-axis label example

代码如下:

D_max_ratio=numpy.divide(D_max_Nobs,D_max_1000) 
fig = plt.figure() 
plt.set_cmap('jet_r') 
x_axis = ['100', '', '300',  '',"500","","700","","900","","1100","","1300","","1500"] 
y_axis = ['10', '20', '30', '40',"50","60","70","80","90","100"] 
ax = fig.add_subplot(111) 
cax = ax.matshow(D_max_ratio) 
ax.xaxis.set_ticks_position('bottom') 
ax.set_xticks(numpy.arange(15)) 
ax.set_yticks(numpy.arange(10)) 
ax.set_xticklabels(x_axis) 
ax.set_yticklabels(y_axis) 
plt.xlabel('f/MHz') 
plt.ylabel('$N_{obs}^{R}$') 
cb=fig.colorbar(cax) 

请您参考如下方法:

您要的是寄生虫轴,如图 example 所示。 ,对于你的情况是,

from mpl_toolkits.axes_grid1 import host_subplot 
import mpl_toolkits.axisartist as AA 
import matplotlib.pyplot as plt 
import numpy as np 
 
#Setup a host axis 
host = host_subplot(111, axes_class=AA.Axes) 
plt.subplots_adjust(bottom=0.2) 
 
#Add twin y axis with offset from bottom and hide top axis 
par = host.twiny() 
offset = -30 
new_fixed_axis = host.get_grid_helper().new_fixed_axis 
par.axis["bottom"] = new_fixed_axis(loc="bottom", 
                                    axes=par, 
                                    offset=(0, offset)) 
par.axis["top"].set_visible(False) 
 
# Plot data and add main axis labels/limits 
host.imshow(np.random.rand(128,1600)) 
host.set_xlabel("f/MHz") 
host.set_xlim((0,1600)) 
plt.axis("tight") 
 
#Set limits of parasite axis  
#(note this axis is not attached to  
# an actual plot so changes nothing) 
 
par.set_xlabel("Ka") 
par.set_xlim((0,15.71)) 
 
plt.draw() 
plt.show() 

看起来像,