使用对数比例时,matplotlib辅助轴反转

jjjwad0x  于 2023-02-09  发布在  其他
关注(0)|答案(1)|浏览(144)

以对数比例绘图时,matplotlib辅助轴会反转。
在所附的例子中,我使用星等作为主(左)轴,亮度作为次(右)轴。较高的亮度应该对应较小的星等,就像在前两个图中一样。然而,在第三个图中,当我使用亮度的对数刻度时,亮度随着星等增加,这是不正确的。这是一个bug,还是我做错了什么?

# Test secondary axis
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
print(matplotlib.__version__)

# Mag to luminosity (solar units) conversion
M_sun = 4.83

def mag2lum(mag):
    return 10**(0.4*(M_sun - mag))

def lum2mag(L):
    return M_sun - 2.5*np.log10(L)

def mag2lgl(mag):
    return 0.4*(M_sun - mag)

def lgl2mag(lgl):
    return M_sun - 2.5*lgl

# log luminosity as second axis - correct behaviour
fig, ax = plt.subplots(constrained_layout=True)
plt.ylabel(r'$M_G$ [mag]')
plt.xlim(-1, 5)
plt.ylim(10, 0)
secax = ax.secondary_yaxis('right', functions=(mag2lgl, lgl2mag))
secax.set_ylabel(r'$\log\ L_G\ [L_\odot]$')
plt.show()

# luminosity as second axis - correct behaviour, but labelling is horrible
fig, ax = plt.subplots(constrained_layout=True)
plt.ylabel(r'$M_G$ [mag]')
plt.xlim(-1, 5)
plt.ylim(10, 0)
secax = ax.secondary_yaxis('right', functions=(mag2lum, lum2mag))
secax.set_ylabel(r'$L_G\ [L_\odot]$')
plt.show()

# luminosity as second axis on log scale: axis is reversed
fig, ax = plt.subplots(constrained_layout=True)
plt.ylabel(r'$M_G$ [mag]')
plt.xlim(-1, 5)
plt.ylim(10, 0)
secax = ax.secondary_yaxis('right', functions=(mag2lum, lum2mag))
secax.set_ylabel(r'$L_G\ [L_\odot]$')
secax.set_yscale('log')
plt.show()

log luminosity as second axis - correct behaviourluminosity as second axis - correct behaviour, but labelling is horribleluminosity as second axis on log scale: axis is reversed
在第三个图中,光度应该向上增加。

hts6caw3

hts6caw31#

在一个y轴的简单情况下,你确实可以设置比例。但是,注意这里发生的事情,在你的第三个例子中。“比例”不是绘图的决定,而是在主y轴和次轴之间转换的函数的结果。我的意思是次轴中的值和它们的位置是“锁定”的,因为它们需要匹配主轴中的对应项。因此,您需要做的不是尝试更改次轴,而是更改其刻度和标签。为此,您可以使用自定义刻度位置标签,或者,如下所述,导入预定义的定位器和格式化程序。

import numpy as np
import matplotlib.pyplot as plt

from matplotlib.ticker import LogLocator, LogFormatterMathtext

M_sun = 4.83

def mag2lum(mag):
    return 10**(0.4*(M_sun - mag))

def lum2mag(L):
    return M_sun - 2.5*np.log10(L)

fig, ax = plt.subplots(constrained_layout=True)
ax.set_ylabel(r'$M_G$ [mag]')
ax.set_xlim(-1, 5)
ax.set_ylim(10, 0)
secax = ax.secondary_yaxis('right', functions=(mag2lum, lum2mag))
secax.set_ylabel(r'$L_G\ [L_\odot]$')

# do this instead of trying to set scale
secax.yaxis.set_major_locator(LogLocator())
secax.yaxis.set_major_formatter(LogFormatterMathtext())

plt.show()

相关问题