我想要类似于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-ticks,而是希望让它们移位。 即,我希望在1000,100,10,1的位置具有顶部主要的x-ticks,并且相应的小标记相应地移动。
这就是我喜欢它的样子:
我找到了这个情节,这就是我想要的! http://inspirehep.net/record/877424/files/fig2.png 注意,因为lambda = c / f和ax& ax_top是对数的,小刻度线的间距必须反转为!
答案 0 :(得分:1)
诀窍是选择你想要的波长并将它们转换成频率。然后使用这些频率作为上标记的位置。
#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)
结果如下图所示: