gpt4 book ai didi

python - Matplotlib:生成多个具有不同和倒比例尺的双轴

转载 作者:太空宇宙 更新时间:2023-11-04 05:52:18 26 4
gpt4 key购买 nike

我想在两个 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()

关于python - Matplotlib:生成多个具有不同和倒比例尺的双轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29587374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com