如何格式化Semilogx子图中的刻度标签

时间:2019-11-02 19:51:31

标签: python matplotlib formatting subplot

我正在尝试将具有两个子图的图形的x_ticks标签更改为标量值。 也就是说,我想将10**010**1分别更改为110

此外,我想设置其余的刻度标签[1,2,3,4,5,6,7,8,9,10]

数字代码是这样的:

%matplotlib inline
import matplotlib.ticker
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
import pylab as pl
plt.rcParams['axes.linewidth'] = 0.3 #set the value globally
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.ticker import ScalarFormatter

h1 = 1.5
h2 = 0.5
fig, (ax1,ax2) = plt.subplots(nrows=2, figsize=(8,10))

#---- 
D = np.arange(0.5, 14.0, 0.0100)
r = np.sqrt((h1-h2)**2 + D**2)
freq = 865.7 
#freq = 915 #MHz
lmb = 300/freq 
q_e = 4*(np.sin(2*np.pi*h1*h2/lmb/D))**2
q_e_rcn1 = 1
P_x_G = 4 # 4 Watt EIRP
sigma = 1.56 #1.94dB
N_1 = np.random.normal(0,sigma,D.shape)
rnd = 10**(-N_1/10)
F = 10 #10

plt.subplot(211)

#
y = 10*np.log10(  1000*(4*1.622*(lmb)**2)/((4*np.pi*r)**2))
plt.semilogx(r, y,label='FLink' )

# 
y = 10*np.log10( 1000*(P_x_G*1.622*((lmb)**2) *0.5*1) / (((4*np.pi*r)**2) *1.2*1*F)*q_e*rnd*q_e_rcn1 )
plt.semilogx(r,y, label='OCM')

plt.axhline(y = -17, linewidth=1.2, color='black',ls='--')
plt.annotate("Threshold",fontsize=13,
             ha = 'center', va = 'bottom',
             xytext = (8.5, -40),
             xy = (4.75, -17),
             arrowprops = dict(arrowstyle="->",
                            connectionstyle="arc3"),
            )

plt.ylabel('Power, $P_t$ [dBm]', fontsize=15, labelpad=10)
plt.tick_params(labelsize=13)
plt.grid(True,which="both",ls=":")
plt.legend(loc='lower left', fontsize=13)
ax1.set_xticks([2, 3, 4, 6, 10])
ax1.get_xaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())
ax1.set_xticklabels(["2", "3", "4","6", "10"])


#----
plt.subplot(212)
rd =np.sqrt((h1-h2)**2 + D**2)
rd = np.sort(rd)
P_r=0.8
G_r=5 
q_e_rcn2 = 1
N_2 = np.random.normal(0, sigma*2, D.shape)
rnd_2 = 10**(-N_2/10)
F_2 = 32 
M = 0.25

# Back link
pwf = 10*np.log10( 1000*(P_r*(G_r*1.622)**2*lmb**4)/(4*np.pi*rd)**4 )
plt.semilogx(rd, pwf,label='FLink' )

## 
y = 10*np.log10(  1000*(P_r*(G_r*1.622)**2*(lmb)**4*0.5**2*M)/((4*np.pi*rd)**4*1.2**2*1**2*F_2)*
        q_e**2*rnd*rnd_2*q_e_rcn1*q_e_rcn2  )
plt.semilogx(rd, y, label='B_D Link' )

# 
plt.axhline(y = -80, linewidth=1.2, color='black',ls='--')
plt.annotate("Threshold",fontsize=13,
             ha = 'center', va = 'bottom',
             xytext = (8, -115),
             xy = (7, -80),
             arrowprops = dict(arrowstyle="->",
                            connectionstyle="arc3"),
            )
plt.xlabel('Distance, r [m]', fontsize=15)
plt.ylabel('Received Pow., $P_R$ [dBm]', fontsize=15)
plt.grid(True,which="both",ls=":")
plt.tick_params(labelsize=13)
plt.legend(loc='lower left', fontsize=13)
ax2.set_xticks([2, 3, 4, 6, 10])
ax2.get_xaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())
ax2.set_xticklabels(["2", "3", "4","6", "10"])

plt.show()

我尝试了其他帖子,例如Matplotlib log scale tick label number formatting 但这在我的情节中不起作用。

例如, 我尝试过

MWE_1

from mpl_toolkits.axes_grid1 import make_axes_locatable
ax2.get_xaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())

还有其他变化

MWE_2

from matplotlib.ticker import ScalarFormatter
for axis in [ax1.xaxis, ax2.xaxis]:
    axis.set_major_formatter(ScalarFormatter())

还有这个解决方案

MWE_3

import matplotlib.ticker
ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.get_xaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())

所有这些MWE都使上述代码的图形具有相同的x_tick标签格式。

致谢。

1 个答案:

答案 0 :(得分:1)

这是带有指数刻度标签的mcve:

import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt

x = np.array([10**i for i in range(10)])
y = np.arange(x.shape[0])
fig,(ax1,ax2) = plt.subplots(nrows=2,ncols=1)
fig.subplots_adjust(wspace=0.7, hspace=0.6)

ax1.plot(x,y)
ax2.plot(x,y*3)

ax1.semilogx()
ax2.semilogx()

还有两种格式化xaxis刻度标签的方法。

# scaler formatter
f1 = mpl.ticker.ScalarFormatter()
f1.set_scientific(False)
ax1.xaxis.set_major_formatter(f1)

# string formatter
f2 = mpl.ticker.StrMethodFormatter('{x:.0f}')
ax2.xaxis.set_major_formatter(f2)

plt.show()
plt.close()