如何在 matplotlib 中添加第二个 x 轴 [英] How to add a second x-axis in matplotlib

查看:47
本文介绍了如何在 matplotlib 中添加第二个 x 轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题.我需要在我的绘图上有第二个 x 轴,我希望这个轴有一定数量的 tic,对应于第一个轴的特定位置.

I have a very simple question. I need to have a second x-axis on my plot and I want that this axis has a certain number of tics that correspond to certain position of the first axis.

让我们尝试一个例子.在这里,我将暗物质质量绘制为膨胀因子的函数,定义为 1/(1+z),范围从 0 到 1.

Let's try with an example. Here I am plotting the dark matter mass as a function of the expansion factor, defined as 1/(1+z), that ranges from 0 to 1.

semilogy(1/(1+z),mass_acc_massive,'-',label='DM')
xlim(0,1)
ylim(1e8,5e12)

我想在图的顶部有另一个 x 轴,显示某些扩展因子值的相应 z.那可能吗?如果是,我怎么能有 xtics ax

I would like to have another x-axis, on the top of my plot, showing the corresponding z for some values of the expansion factor. Is that possible? If yes, how can I have xtics ax

推荐答案

我从@Dhara 的回答中的评论中得到了提示,听起来您想通过以下方式设置 new_tick_locations 列表从旧 x 轴到新 x 轴的函数.下面的 tick_function 接受一个 numpy 点数组,将它们映射到一个新值并格式化它们:

I'm taking a cue from the comments in @Dhara's answer, it sounds like you want to set a list of new_tick_locations by a function from the old x-axis to the new x-axis. The tick_function below takes in a numpy array of points, maps them to a new value and formats them:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

X = np.linspace(0,1,1000)
Y = np.cos(X*20)

ax1.plot(X,Y)
ax1.set_xlabel(r"Original x-axis: $X$")

new_tick_locations = np.array([.2, .5, .9])

def tick_function(X):
    V = 1/(1+X)
    return ["%.3f" % z for z in V]

ax2.set_xlim(ax1.get_xlim())
ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(tick_function(new_tick_locations))
ax2.set_xlabel(r"Modified x-axis: $1/(1+X)$")
plt.show()

这篇关于如何在 matplotlib 中添加第二个 x 轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆