python / matplotlib - 寄生虫双轴缩放

时间:2010-06-30 11:33:51

标签: python matplotlib axes

尝试绘制光谱,即速度与强度,x轴较低=速度,在上双轴=频率

它们之间的关系(多普勒公式)是

f = (1-v/c)*f_0 

其中f是结果频率,v是速度,c是光速,f_0是v = 0时的频率,即。 v_lsr。

我试图通过查看http://matplotlib.sourceforge.net/examples/axes_grid/parasite_simple2.html来解决它,它由

解决
pm_to_kms = 1./206265.*2300*3.085e18/3.15e7/1.e5
aux_trans = matplotlib.transforms.Affine2D().scale(pm_to_kms, 1.)
ax_pm = ax_kms.twin(aux_trans)
ax_pm.set_viewlim_mode("transform")

我的问题是,如何用频率函数替换pm_to_kms?

任何人都知道如何解决这个问题?

2 个答案:

答案 0 :(得分:5)

我最终使用的解决方案是:

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单位等效性,它变得更容易理解和更具说明性。

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

答案 1 :(得分:0)

您的“线性函数”是“简单缩放法则”(带偏移量)。只需将pm_to_kms定义替换为您的函数。