簡體   English   中英

如何在 matplotlib 中添加第二個 x 軸

[英]How to add a second x-axis in matplotlib

我有一個非常簡單的問題。 我需要在我的繪圖上有第二個 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

我從@Dhara 的回答中的評論中得到了一個提示,聽起來您想通過從舊 x 軸到新 x 軸的函數設置new_tick_locations列表。 下面的tick_function接受一個 numpy 點數組,將它們映射到一個新值並格式化它們:

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()

在此處輸入圖片說明

您可以使用 twiny 創建 2 個 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

輸出:在此處輸入圖片說明

如果您希望上軸是下軸刻度值的函數,您可以執行以下操作。 請注意:有時get_xticks()會有可見范圍之外的刻度,您在轉換時必須考慮到這一點。

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()
ax2.set_xticks( ax1.get_xticks() )
ax2.set_xbound(ax1.get_xbound())
ax2.set_xticklabels([x * 2 for x in ax1.get_xticks()])

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")

給出:

在此處輸入圖片說明

在 Dhara 的回答評論中回答您的問題:“我想在第二個 x 軸上這些抽動:(7,8,99) 對應於 x 軸位置 10、30、40。這在某種程度上可能嗎? ”是的, 這是。

import numpy as np
import matplotlib.pyplot as plt

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

a = np.cos(2*np.pi*np.linspace(0, 1, 60.))
ax1.plot(range(60), a)

ax1.set_xlim(0, 60)
ax1.set_xlabel("x")
ax1.set_ylabel("y")

ax2 = ax1.twiny()
ax2.set_xlabel("x-transformed")
ax2.set_xlim(0, 60)
ax2.set_xticks([10, 30, 40])
ax2.set_xticklabels(['7','8','99'])

plt.show()

你會得到:在此處輸入圖片說明

從 matplotlib 3.1 開始,您可以使用ax.secondary_xaxis

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1,13, num=301)
y = (np.sin(x)+1.01)*3000

# Define function and its inverse
f = lambda x: 1/(1+x)
g = lambda x: 1/x-1

fig, ax = plt.subplots()
ax.semilogy(x, y, label='DM')

ax2 = ax.secondary_xaxis("top", functions=(f,g))

ax2.set_xlabel("1/(x+1)")
ax.set_xlabel("x")
plt.show()

由於聲譽低,我被迫將此作為答案而不是評論發布。 我遇到了與 Matteo 類似的問題。 不同之處在於我沒有從第一個 x 軸到第二個 x 軸的映射,只有 x 值本身。 所以我想直接在我的第二個 x 軸上設置數據,而不是刻度,但是,沒有axes.set_xdata 我能夠使用 Dhara 的答案通過修改來做到這一點:

ax2.lines = []

而不是使用:

ax2.cla()

在使用時也從ax1清除了我的情節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM