2015-04-12 21 views
2

我想繪製兩個x軸和y軸上的數據序列,以獲得4個不同的軸。 首先x(能量以eV爲單位)對y(歸一化計數)軸,然後x(與能量成反比的波長)對y(計數)軸。 我對這個代碼是:Matplotlib:生成具有不同的倒數比例的多個雙軸

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.mlab as mlab 
from scipy.constants import h, c, e 


def E(wavelength): 
    return (h*c)/(wavelength*e) 

wavelen = np.linspace(800e-9,1600e-9,200) 
E_eV = E(wavelen) 
loc, scale = 950e-9, 3.0 
counts = mlab.normpdf(wavelen,950e-9,100e-9)/100 
counts_norm = counts/10000 


fig, ax = plt.subplots() 

ax1 = ax 
ax2 = ax.twinx() 
ax3 = ax.twiny() 

plt.ticklabel_format(style='sci', scilimits=(0,0)) 

ax1.plot(E_eV, counts_norm) 
ax1.set_xlim(E(1600e-9),E(800e-9)) 
ax1.set_ylabel('normalized counts') 
ax1.set_xlabel('energy (eV)') 
ax2.plot(E_eV, counts) 
ax2.set_xlim(E(1600e-9),E(800e-9)) 
ax2.set_ylabel('counts') 
ax3.plot(wavelen*1e9, counts_norm) 
ax3.set_xlim(1600,800) 
ax3.set_xlabel('wavelength (nm)') 
ax3.ticklabel_format(style='plain') 


plt.tight_layout() 
plt.show() 

正如你所看到的曲線不正確的方式縮放,使得它們重疊,並在X方向相同的尺寸。 你能幫助我如何爲頂部的x(波長)軸設置正確的參數嗎?

回答

0

我建議只繪製在您的主軸上,然後同步雙軸的標籤。我編輯了你的例子來展示靜態情節如何實現。

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.mlab as mlab 
from scipy.constants import h, c, e 

def E(wavelength): 
    return (h*c)/(wavelength*e) 
def getWaveLength(energy): 
    return (h*c)/(energy*e) 
def getCounts(normcounts): 
    return normcounts*1000 

wavelen = np.linspace(800e-9,1600e-9,200) 
E_eV = E(wavelen) 
loc, scale = 950e-9, 3.0 
counts = mlab.normpdf(wavelen,950e-9,100e-9)/100 
counts_norm = counts/10000 

fig, ax1 = plt.subplots() 

ax2 = ax1.twinx() 
ax3 = ax1.twiny() 

plt.ticklabel_format(style='sci', scilimits=(0,0)) 

ax1.plot(E_eV, counts_norm) 
ax1.set_xlim(E(1600e-9),E(800e-9)) 
ax1.set_ylabel('normalized counts') 
ax1.set_xlabel('energy (eV)') 
ax2.set_ylabel('counts') 
ax3.set_xlabel('wavelength (nm)') 
ax3.ticklabel_format(style='plain') 

# get the primary axis x tick locations in plot units 
xtickloc = ax1.get_xticks() 
# set the second axis ticks to the same locations 
ax3.set_xticks(xtickloc) 
# calculate new values for the second axis tick labels, format them, and set them 
x2labels = ['{:.3g}'.format(x) for x in getWaveLength(xtickloc)] 
ax3.set_xticklabels(x2labels) 
# force the bounds to be the same 
ax3.set_xlim(ax1.get_xlim()) 

#same for y 
ytickloc = ax1.get_yticks() 
ax2.set_yticks(ytickloc) 
ax2.set_yticklabels([str(int(y)) for y in getCounts(ytickloc)]) 
ax2.set_ylim(ax1.get_ylim()) 

plt.tight_layout() 
plt.show() 
+0

靜態軸可以是一個解決方案,但實際上我想格式化程序捆綁在我的例子方法成一個功能,並定期調用它會自動計算出蜱 – beneminzl

+0

我在我的應用程序交互做到了用[timer](http://matplotlib.org/api/backend_bases_api.html?highlight=new_timer#matplotlib.backend_bases.FigureCanvasBase.new_timer)。 –

相關問題