簡體   English   中英

Matplotlib:生成具有不同比例和反向比例的多個雙軸

[英]Matplotlib: generate multiple twin axes with different and inverted scale

我想在兩個x和y軸上繪制數據序列,以便具有4個不同的軸。 首先是x(以eV為單位的能量)與y(歸一化的計數)軸,然后是x(與能量成反比的波長)與y(計數)軸。 我的代碼是:

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(波長)軸設置正確的參數嗎?

我建議僅在主軸上繪制,然后同步雙軸的標簽。 我編輯了您的示例,以顯示如何針對靜態圖完成此操作。

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM