我結束了使用的解決方案是:
ax_hz = ax_kms.twiny()
x_1, x_2 = ax_kms.get_xlim()
# i want the frequency in GHz so, divide by 1e9
ax_hz.set_xlim(calc_frequency(x_1,data.restfreq/1e9),calc_frequency(x_2,data.restfreq/1e9))
這完美的作品,以及更復雜的解決方案。
編輯:找到了一個非常奇特的答案。 EDIT2:根據@ U55
這基本上是定義我們自己的轉換註釋改變了變換呼叫/變換。由於AstroPy Units的優秀等價性,它變得更容易理解和更具說明性。
from matplotlib import transforms as mtransforms
import astropy.constants as co
import astropy.units as un
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
from mpl_toolkits.axes_grid.parasite_axes import SubplotHost
class Freq2WavelengthTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = False
has_inverse = True
def __init__(self):
mtransforms.Transform.__init__(self)
def transform_non_affine(self, fr):
return (fr*un.GHz).to(un.mm, equivalencies=un.spectral()).value
def inverted(self):
return Wavelength2FreqTransform()
class Wavelength2FreqTransform(Freq2WavelengthTransform):
input_dims = 1
output_dims = 1
is_separable = False
has_inverse = True
def __init__(self):
mtransforms.Transform.__init__(self)
def transform_non_affine(self, wl):
return (wl*un.mm).to(un.GHz, equivalencies=un.spectral()).value
def inverted(self):
return Freq2WavelengthTransform()
aux_trans = mtransforms.BlendedGenericTransform(Wavelength2FreqTransform(), mtransforms.IdentityTransform())
fig = plt.figure(2)
ax_GHz = SubplotHost(fig, 1,1,1)
fig.add_subplot(ax_GHz)
ax_GHz.set_xlabel("Frequency (GHz)")
xvals = np.arange(199.9, 999.9, 0.1)
# data, noise + Gaussian (spectral) lines
data = np.random.randn(len(xvals))*0.01 + np.exp(-(xvals-300.)**2/100.)*0.5 + np.exp(-(xvals-600.)**2/400.)*0.5
ax_mm = ax_GHz.twin(aux_trans)
ax_mm.set_xlabel('Wavelength (mm)')
ax_mm.set_viewlim_mode("transform")
ax_mm.axis["right"].toggle(ticklabels=False)
ax_GHz.plot(xvals, data)
ax_GHz.set_xlim(200, 1000)
plt.draw()
plt.show()
現在,這產生了預期的效果: ![enter image description here](https://i.stack.imgur.com/yOqL1.png)
偶然發生這種情況是正確的,因爲頻率和波長(νλ= c)之間的轉換方程關於頻率和波長的交換是對稱的。但是,對於一般轉換,這會產生不正確的結果。 此時應更換'Freq2WavelengthTransform()'和'Wavelength2FreqTransform()'該行: 'aux_trans = mtransforms.BlendedGenericTransform(Freq2WavelengthTransform(),mtransforms.IdentityTransform())'。 – u55 2016-10-13 06:03:37