2024-05-29 00:12:08 发布
网友
我有一个很简单的问题。我需要在我的图上有第二个x轴,我希望这个轴有一定数量的tic,对应于第一个轴的特定位置。
让我们举个例子。在这里,我绘制暗物质质量,作为膨胀因子的函数,定义为1/(1+z),范围从0到1。
semilogy(1/(1+z),mass_acc_massive,'-',label='DM') xlim(0,1) ylim(1e8,5e12)
我想在我的图的顶部有另一个x轴,显示一些膨胀系数值对应的z。有可能吗?如果是,我怎么能有xtics ax
可以使用twiny创建两个x轴比例。例如:
import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(111) ax2 = ax1.twiny() a = np.cos(2*np.pi*np.linspace(0, 1, 60.)) ax1.plot(range(60), a) ax2.plot(range(100), np.ones(100)) # Create a dummy plot ax2.cla() plt.show()
参考号:http://matplotlib.sourceforge.net/faq/howto_faq.html#multiple-y-axis-scales
输出:
我从@Dhara的答案中得到一个提示,听起来你想通过一个从旧x轴到新x轴的函数设置一个new_tick_locations列表。下面的tick_function接受点的numpy数组,将它们映射到新值并格式化它们:
new_tick_locations
tick_function
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()
如果希望上轴是下轴刻度值的函数:
import matplotlib.pyplot as plt fig, ax1 = plt.subplots() ax1 = fig.add_subplot(111) ax1.plot(range(5), range(5)) ax1.grid(True) ax2 = ax1.twiny() ax1Xs = ax1.get_xticks() ax2Xs = [] for X in ax1Xs: ax2Xs.append(X * 2) ax2.set_xticks(ax1Xs) ax2.set_xbound(ax1.get_xbound()) ax2.set_xticklabels(ax2Xs) title = ax1.set_title("Upper x-axis ticks are lower x-axis ticks doubled!") title.set_y(1.1) fig.subplots_adjust(top=0.85) fig.savefig("1.png")
给出:
可以使用twiny创建两个x轴比例。例如:
参考号:http://matplotlib.sourceforge.net/faq/howto_faq.html#multiple-y-axis-scales
输出:
我从@Dhara的答案中得到一个提示,听起来你想通过一个从旧x轴到新x轴的函数设置一个
new_tick_locations
列表。下面的tick_function
接受点的numpy数组,将它们映射到新值并格式化它们:如果希望上轴是下轴刻度值的函数:
给出:
相关问题 更多 >
编程相关推荐