我有以下代码片段可以用 logscale 为 x-axis 进行绘图:
# Number of values for loop
num_prior_loop = 100
# Declare prior array
prior_fish = np.zeros(num_prior_loop)
prior_start = 0
prior_end = 3
prior_fish = np.logspace(prior_start,prior_end,num_prior_loop)**2
# Declare FoM final array
FoM_final = np.zeros(num_prior_loop)
...
# Plot
fig, ax = plt.subplots()
ax.plot(prior_fish, FoM_final)
#ax.set_xticks([np.linspace(prior_start,prior_end)])
#ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
plt.xlabel(r'Prior on 5 ratios '+r'$\alpha = b_{sp}/b_{ph}$'+' in Fisher GCsp', fontsize=10)
plt.ylabel('FoM')
plt.title('FoM vs Prior - Prior on both GCsp and XC', fontsize=10)
plt.savefig('FoM_vs_Prior_alpha_on_both_GCsp_and_XC.pdf')
产生下图:
现在,我想做一个修改,就是想把xtick 10^0 up to 10^6 自动替换为1, 10^-1, 10^-2, ...., 10^- 6.
我会自动说,因为 2 个边界(1 和 10^-6)的开始和结束可能会有所不同。
更新1:我尝试了@max
下面答案中建议的解决方案,但失败了:
这是我得到的:
如果我做 :
for txt in axs.get_xticklabels():
# get position
x,y = txt.get_position()
print('x,y =', x,y)
# value/formatting
val = txt.get_text()
# create new label
if x == 1 or x == 0:
val_new = f'${round(x)}$'
else:
val_new = '$\\mathdefault{10^{' + f'{round(np.log10(1/x))}' + '}}$'
# append
xTickLabel.append( Text(x,y,val_new) )
# set labels
axs.set_xticklabels( xTickLabel )
# Plot and save
plt.plot(prior_fish, FoM_final)
plt.draw()
plt.savefig('FoM_vs_Prior_alpha_on_both_GCsp_and_XC.png')
我只得到零:
x,y = 0 0
x,y = 0 0
x,y = 0 0
x,y = 0 0
x,y = 0 0
x,y = 0 0
x,y = 0 0
x,y = 0 0
x,y = 0 0
x,y = 0 0
x,y = 0 0
x,y = 0 0
并且打印val
总是返回空值。
这里是整个代码:
# Plot
fig, axs = plt.subplots()
axs.set_xscale('log')
plt.draw()
plt.xlabel(r'Prior on 5 ratios '+r'$\alpha = b_{sp}/b_{ph}$'+' in Fisher GCsp', fontsize=10)
plt.ylabel('FoM')
plt.title('FoM vs Prior - Prior on both GCsp and XC', fontsize=10)
# create new labels
xTickLabel = []
for txt in axs.get_xticklabels():
# get position
x,y = txt.get_position()
# value/formatting
val = txt.get_text()
# create new label
if x == 1 or x == 0:
val_new = f'${round(x)}$'
else:
val_new = '$\\mathdefault{10^{' + f'{round(np.log10(1/x))}' + '}}$'
# append
xTickLabel.append( Text(x,y,val_new) )
# set labels
axs.set_xticklabels( xTickLabel )
# Plot and save
plt.plot(prior_fish, FoM_final)
plt.draw()
plt.savefig('FoM_vs_Prior.pdf')
错误在哪里?如何获取“0”和“1”的不同值以避免出现这种情况
if x == 1 or x == 0:
val_new = f'${round(x)}$'