多个彼此非线性的 x 轴

6 投票
2 回答
4066 浏览
提问于 2025-04-17 15:41

我想用matplotlib画一个图,这个图有两个x轴,而且这两个x轴之间的关系不是线性的。也就是说,它们的变化不是简单的直线关系。想要的效果是这样的:

Plot

简单来说,年龄是依赖于红移的,这种关系是非线性的,需要进行计算。我想把年龄和红移都作为x轴。请问我该怎么做呢?

2 个回答

0

我这样做的:

from mpl_toolkits.axes_grid.parasite_axes import SubplotHost 
fig = plt.figure(1, figsize=(figwidth,figheight))
ax = SubplotHost(fig, 1,1,1) 
fig.add_subplot(ax)

#plotting as usual

ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis
ax2.axis["right"].toggle(ticklabels=False)
ax2.xaxis.set_major_formatter(FuncFormatter(fmt_zToEta)) #set eta coord format

#with a function for the Z to eta transform for plot labels
def fmt_zToEta(x, pos=None):
    #...
    return transformed_label 

我还记得一开始用那个红移的例子 ;-)

我觉得这个 SubPlotHost 的东西是必要的,但我不是百分之百确定,因为我是在没有检查它是否能正常运行的情况下,从我现有的(子)图中提取出来的。

编辑:另外,可以看看 这个链接

4

你可能需要的函数是 twiny()

import matplotlib.pyplot as plt
plt.loglog(range(100))
ax1 = plt.gca()
ax2 = ax1.twiny()
ax2.set_xticks([100,80,50])
ax2.set_xticklabels(['0','1','2'])
ax1.set_xlabel('redshift')
ax2.set_xlabel('age')
plt.show()

twiny()函数的示例图

撰写回答