我想要类似于How to add a second x-axis in matplotlib的东西,即具有显示波长的顶部 x 轴和显示相应频率的底部轴。
该图是用以下内容生成的:
#setting up the plot
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.gridspec as gridspec
fig = plt.figure()
fig.tight_layout()
ax = plt.subplot()
#Here it gets interesting!
def tick_function(X):
c = 299792458
V = c/X
V = V*1e6
V = np.round(V,0)
V[2] = 3000
V = V.astype(int)
return(V)
ax = plt.subplot()
ax_top = ax.twiny()
ax.set_xscale("log", nonposx='clip')
ax.set_yscale("log", nonposy='clip')
ax_top.set_xscale("log", nonposx='clip')
ax.set_xlim([8e10,5e14])
ax.set_ylim([5e33,2e36])
axTicks = ax.get_xticks()
ax_top_Ticks = axTicks
ax_top.set_xticks(ax_top_Ticks)
ax_top.set_xlim(ax.get_xlim())
ax_top.set_xbound(ax.get_xbound())
ax_top.set_xticklabels(tick_function(ax_top_Ticks))
现在,我不想在底部主要x轴的位置绘制顶部主要x刻度,而是想让它们移动。 即,我希望顶部主要 x 刻度位于位置 1000、100、10、1 处,并且次要刻度相应地移动。
<小时/>这也是我想要的样子:
我找到了这个情节,这就是我想要的! http://inspirehep.net/record/877424/files/fig2.png 请注意,由于 lambda=c/f 和 ax & ax_top 是对数,因此小刻度的间距必须反转!
最佳答案
诀窍是选择您想要的波长并将其转换为频率。然后使用这些频率作为上部刻度的位置。
#setting up the plot
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure()
ax = plt.subplot()
def conversion_freq_lam(inp):
c = 299792458
outp = c/inp
outp = outp.astype(int)
return outp
#ax = plt.subplot(gs1[0])
ax = plt.subplot(111)
ax_top = ax.twiny()
ax.set_xscale("log", nonposx='clip')
ax.set_yscale("log", nonposy='clip')
ax_top.set_xscale("log", nonposx='clip')
ax.set_xlim([8e10,5e14])
ax.set_ylim([5e33,2e36])
goal_lambdas = np.array([100000, 10000, 1000, 100, 10, 1, 0.1, 0.01])
goal_freqs = conversion_freq_lam(goal_lambdas)
ax_top_Ticks = goal_freqs * 1e6 # magic factor 1e6 from your attempt. Units?
ax_top.set_xticks(ax_top_Ticks)
ax_top.set_xlim(ax.get_xlim())
ax_top.set_xbound(ax.get_xbound())
ax_top.set_xticklabels(goal_lambdas)
plt.savefig('test_2axes.png')
我从你的问题中获取了用作比例因子的神奇数字1e6
。我认为这是由轴的单位引起的。
编辑:
要在顶轴上有正确间隔的小刻度(例如在 2、3、4、...、20、30、40、50、...),请添加以下代码块:
def find_minor_vals(goals):
minors = []
factors = np.arange(2, 10, 1)
for val in goals:
minors.extend(list(val * factors))
print minors
return np.array(minors)
goal_lambdas_minor = find_minor_vals(goal_lambdas)
goal_freqs_minor = conversion_freq_lam(goal_lambdas_minor) * 1e6
minor_locator = FixedLocator(goal_freqs_minor)
ax_top.xaxis.set_minor_locator(minor_locator)
结果如下图:
关于python - 将顶部主要 x 刻度的位置更改为底部轴的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48191134/